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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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;
    }
}
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) —

GD Star Rating
loading...
202 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

Leave a Reply