String StartsWith Implementation in Java
In Java, we can use the String's extension method startsWith to check if it starts with a prefix. We can even specify the start position for the string matching comparison.
Have you wondered how these methods are implemented in JDK? See below:
public class StringUtils {
public boolean startsWith(String prefix, int toffset) {
startsWith(prefix, 0);
}
public boolean startsWith(String prefix, int toffset) {
char ta[] = value;
var to = toffset;
char pa[] = prefix.value;
int po = 0;
var pc = prefix.value.length;
if ((toffset < 0) || (toffset > value.length - pc)) {
return false;
}
while (--pc >= 0) {
if (ta[to++] != pa[po++]) {
return false;
}
}
return true;
}
}
No tricks are used - simply comparing character by character for the prefix and the string to see if both matches. The time complexity is O(N) where N is the number of characters in prefix.
Reposted to Blog
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Thank you for reading ^^^^^^^^^^^^^^^
NEW! Following my Trail (Upvote or/and Downvote)
Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com
My contributions
- Video Downloader
- Steem Blockchain Tools
- Free Cryptos API
- VPS Database
- Computing Technology Blog
- A few useless tools
- And some other online software/tools
- Merge Files/Videos
- LOGO Turtle Programming Chrome Extension
- Teaching Kids Programming - Youtube Channel and All Contents
Delegation Service
Important Update of Delegation Service!
Support me
If you like my work, please:
- Buy Me a Coffee, Thanks!
- Become my Sponsor, Thanks!
- Voting for me:
https://steemit.com/~witnesses type in justyy and click VOTE
- Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
- Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
- Set @justyy as Proxy: https://steemyy.com/witness-voting/?witness=justyy&action=proxy
Alternatively, you can vote witness or set proxy here: https://steemit.com/~witnesses
Always be succes
고맙습니다^^