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:
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) —
180 wordsLast Post: Teaching Kids Programming - Convert Romans to Integers
Next Post: Teaching Kids Programming - Reverse Sublists to Convert to Target