Java Arena
Step 5 of 8

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]);
Output
5
cats
windows
  • The separator isn't part of any piece: here the spaces are gone.
  • words.length is the number of pieces. No parentheses: it's an array, not a String.
  • words[0] is the first piece and words[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");
Output
2 words have more than 4 letters

Any 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]);
Output
Day 14, month 03, year 2025

Two 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 and b.
  • split reads 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, write split("\\."). Spaces, commas, semicolons, colons, dashes and slashes work just as they are.

Your task

Challenge 1 of 3

Fill in the blanks, so the program counts the words in a line. For the input I like green tea it prints:

Words: 4

Challenge 2

Write a method fileName(String path) that returns the last part of a path: the part after the last /. A path without any / is a file name already. The check runs System.out.println(fileName("photos/2025/beach.jpg")); and expects:

beach.jpg

Challenge 3

Read a phrase and print its acronym: the first letter of every word, in capitals. The words are separated by single spaces. For the input portable network graphics the program prints:

PNG