String StartsWith Implementation in Java

in #java5 years ago

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

Delegation Service

Important Update of Delegation Service!

  • Delegate 1000 to justyy: Link
  • Delegate 5000 to justyy: Link
  • Delegate 10000 to justyy: Link

Support me

If you like my work, please:

  1. Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
  2. Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
  3. 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

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.084
BTC 60162.63
ETH 1576.76
USDT 1.00
SBD 0.42