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.

–EOF (The Ultimate Computing & Technology Blog) —

185 words
Last Post: Teaching Kids Programming - Reverse Sublists to Convert to Target
Next Post: Teaching Kids Programming - Flip to Zeros

The Permanent URL is: String StartsWith Implementation in Java (AMP Version)

Leave a Reply