What split does
The split method cuts a string into pieces wherever a separator appears and returns the pieces as a String[]. It is the standard way to turn a line like "hello world foo" or "a,b,c" into separate values you can loop over.
String sentence = "hello world foo";
String[] words = sentence.split(" ");
// words holds: hello, world, foo
String csv = "a,b,c";
String[] parts = csv.split(",");
// parts holds: a, b, c
The separator itself is not kept in the pieces. The array's length tells you how many pieces there are: words.length is 3. Arrays use length without parentheses, unlike strings, which use length().
To visit each piece, use an enhanced for loop:
for (String w : words) {
System.out.println(w);
}
// hello
// world
// foo
The delimiter is a regular expression
The argument to split is not plain text. It is a regular expression, a pattern. A space or a comma happens to match only itself, so those work as expected. Characters that have a special meaning in patterns do not. The dot, for instance, means "any character":
System.out.println(Arrays.toString("a.b.c".split("."))); // []
System.out.println(Arrays.toString("a.b.c".split("\\."))); // [a, b, c]
The first call treats every character as a separator, so nothing is left and the array is empty. To split on a literal dot, escape it with a backslash, and since a backslash inside a Java string must itself be doubled, write "\\.". The same care applies to |, *, +, ?, (, [ and $. (The examples use Arrays.toString from java.util to print an array.)
The regular expression is also a strength. "\\s+" means "one or more whitespace characters", so it handles repeated spaces, tabs and line breaks in one go:
System.out.println(Arrays.toString("a b".split(" "))); // [a, , b]
System.out.println(Arrays.toString("a b".split("\\s+"))); // [a, b]
With a single space as the separator, two spaces in a row produce an empty string between them.
Using the pieces
The pieces are ordinary strings stored in an array, so you read them by index starting at 0. Splitting a key=value pair is a typical use:
String[] kv = "name=Ann".split("=");
System.out.println(kv[0] + " -> " + kv[1]); // name -> Ann
When the pieces are numbers, combine split with Integer.parseInt to convert each one:
int sum = 0;
for (String p : "4,8,15".split(",")) {
sum += Integer.parseInt(p);
}
System.out.println(sum); // 27
Be careful with the index. If the separator is missing, you get an array with one element, and kv[1] fails with an ArrayIndexOutOfBoundsException. Check kv.length before reading a piece you aren't sure exists.
The lesson's exercise
The starting code has one variable:
String sentence = "hello world foo";
The task is to split it into words, in one step:
- Declare a
String[]namedwordsbelowsentence. The result ofsplitis an array of strings, so that is the variable's type. - Assign it
sentence.split(" "). The sentence has single spaces between the words, so a plain space works as the separator here. The result is the three wordshello,worldandfoo.
The complete code is:
String sentence = "hello world foo";
String[] words = sentence.split(" ");
Gotchas
Most surprises with split come from the regular expression and from empty pieces at the edges of the result.
- Trailing empty strings are dropped.
"a,b,,".split(",")has only two elements,aandb. To keep them, pass a negative limit:"a,b,,".split(",", -1)gives four elements, the last two empty. - Leading empty strings are kept.
",a".split(",")gives an empty string first, thena. The same happens for" hello world".split(" "), which starts with an empty piece. - A string without the separator comes back whole. You get an array with one element. Splitting
""also gives one element, the empty string, not an empty array. - You can limit the number of pieces.
"a-b-c".split("-", 2)stops after two pieces and givesaandb-c. - An empty pattern splits into characters.
"abc".split("")givesa,b,c. - The original string is unchanged, since strings are immutable.
Key takeaways
s.split(regex)returns aString[]of the pieces between separators.- The separator is a regular expression, so escape special characters such as the dot as
"\\.". - Use
"\\s+"to split on runs of whitespace. - Trailing empty strings are removed unless you pass a negative limit.