Splitting a string
Text often holds several values in a row: the words of a sentence, or the day, month and year of a date. split cuts a string at every place where a separator appears, and returns the pieces in an array of Strings, a String[]:
String sentence = "cats like warm sunny windows";
String[] words = sentence.split(" ");
System.out.println(words.length);
System.out.println(words[0]);
System.out.println(words[words.length - 1]);
5
cats
windows- The separator isn't part of any piece: here the spaces are gone.
words.lengthis the number of pieces. No parentheses: it's an array, not a String.words[0]is the first piece andwords[words.length - 1]the last, as in any array.
To handle every piece, loop over the array. The for-each loop works on arrays just like on lists:
String sentence = "a long and winding road leads here";
int longWords = 0;
for (String word : sentence.split(" ")) {
if (word.length() > 4) {
longWords++;
}
}
System.out.println(longWords + " words have more than 4 letters");
2 words have more than 4 lettersAny text can be the separator. A date splits at its dashes:
String date = "2025-03-14";
String[] parts = date.split("-");
System.out.println("Day " + parts[2] + ", month " + parts[1] + ", year " + parts[0]);
Day 14, month 03, year 2025Two things to watch for:
- Two separators in a row have an empty piece between them:
"a b".split(" "), with two spaces, gives three pieces:a, the empty string andb. splitreads its separator as a pattern, in which a few characters have a special meaning. The dot and|are two of them: to split at a dot, writesplit("\\."). Spaces, commas, semicolons, colons, dashes and slashes work just as they are.