Re-Implement the String Split Function In Java


In Java, we can use the handy String’s method Split to split a string by the given delimiter into array of strings. Have you wondered how it is implemented? See below String Split function from JDK:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class StringUtils {
    public static String[] split(String input, char delimiter) {
        var v = new Vector();
        boolean moreTokens = true;
 
        while (moreTokens) {
            int tokenLocation = input.indexOf(delimiter);
            if (tokenLocation > 0) {
                var subString = input.substring(0, tokenLocation);
                v.addElement(subString);
                input = input.substring(tokenLocation + 1);
            } else {
                moreTokens = false;
                v.addElement(input);
            }
        }
 
        var res = new String[v.size()];
 
        for (int i = 0; i != res.length; ++i) {
            res[i] = (String)v.elementAt(i);
        }
 
        return res;
    }
}
public class StringUtils {
    public static String[] split(String input, char delimiter) {
        var v = new Vector();
        boolean moreTokens = true;

        while (moreTokens) {
            int tokenLocation = input.indexOf(delimiter);
            if (tokenLocation > 0) {
                var subString = input.substring(0, tokenLocation);
                v.addElement(subString);
                input = input.substring(tokenLocation + 1);
            } else {
                moreTokens = false;
                v.addElement(input);
            }
        }

        var res = new String[v.size()];

        for (int i = 0; i != res.length; ++i) {
            res[i] = (String)v.elementAt(i);
        }

        return res;
    }
}

We repeatedly search for the delimiter using indexOf function, then push a substring to the vector, and keep doing this until no more token. Then, we convert the vector of tokens into an array.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
197 words
Last Post: Teaching Kids Programming - Convert Romans to Integers
Next Post: Teaching Kids Programming - Reverse Sublists to Convert to Target

The Permanent URL is: Re-Implement the String Split Function In Java

Leave a Reply