{"id":"strings-split","slug":"splitting","title":"Splitting a string","text":"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[]`:\n\n```java\nString sentence = \"cats like warm sunny windows\";\nString[] words = sentence.split(\" \");\nSystem.out.println(words.length);\nSystem.out.println(words[0]);\nSystem.out.println(words[words.length - 1]);\n```\n\n```output\n5\ncats\nwindows\n```\n\n- The separator isn't part of any piece: here the spaces are gone.\n- `words.length` is the number of pieces. No parentheses: it's an array, not a String.\n- `words[0]` is the first piece and `words[words.length - 1]` the last, as in any array.\n\nTo handle every piece, loop over the array. The for-each loop works on arrays just like on lists:\n\n```java\nString sentence = \"a long and winding road leads here\";\nint longWords = 0;\nfor (String word : sentence.split(\" \")) {\n    if (word.length() > 4) {\n        longWords++;\n    }\n}\nSystem.out.println(longWords + \" words have more than 4 letters\");\n```\n\n```output\n2 words have more than 4 letters\n```\n\nAny text can be the separator. A date splits at its dashes:\n\n```java\nString date = \"2025-03-14\";\nString[] parts = date.split(\"-\");\nSystem.out.println(\"Day \" + parts[2] + \", month \" + parts[1] + \", year \" + parts[0]);\n```\n\n```output\nDay 14, month 03, year 2025\n```\n\nTwo things to watch for:\n\n- 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`.\n- `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.\n","task":"Fill in the blanks, so the program counts the words in a line. For the input `I like green tea` it prints:\n\n```\nWords: 4\n```\n","kind":"fill","seed":"import java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        String line = scanner.nextLine();\n        String[] words = line.[[split]](\" \");\n        System.out.println(\"Words: \" + words.[[length]]);\n    }\n}\n","solution":"import java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        String line = scanner.nextLine();\n        String[] words = line.split(\" \");\n        System.out.println(\"Words: \" + words.length);\n    }\n}\n","hints":["`split` cuts the line at every space and returns the pieces as an array.","The size of an array is `length`, without parentheses."],"tests":[{"name":"Test 1","stdin":"I like green tea\n","expect":"Words: 4","hidden":false},{"name":"Test 2","stdin":"Hello\n","expect":"Words: 1","hidden":true},{"name":"Test 3","stdin":"one two three four five six\n","expect":"Words: 6","hidden":true}],"require":[],"forbid":[],"more":[{"task":"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:\n\n```\nbeach.jpg\n```\n","kind":"code","seed":"public class Main {\n    public static void main(String[] args) {\n        System.out.println(fileName(\"photos/2025/beach.jpg\"));\n    }\n\n    // Write the fileName method here.\n}\n","solution":"public class Main {\n    public static void main(String[] args) {\n        System.out.println(fileName(\"photos/2025/beach.jpg\"));\n    }\n\n    public static String fileName(String path) {\n        String[] parts = path.split(\"/\");\n        return parts[parts.length - 1];\n    }\n}\n","hints":["`String[] parts = path.split(\"/\");` cuts the path at every slash.","The last part has the index `parts.length - 1`. A path without a slash splits into one part, which is then the last one too."],"tests":[{"name":"System.out.println(fileName(\"photos/2025/beach.jpg\"));","stdin":"","call":"System.out.println(fileName(\"photos/2025/beach.jpg\"));\n","expect":"beach.jpg","hidden":false},{"name":"System.out.println(fileName(\"notes.txt\"));","stdin":"","call":"System.out.println(fileName(\"notes.txt\"));\n","expect":"notes.txt","hidden":true},{"name":"System.out.println(fileName(\"music/jazz/2024/live/track01.mp3\"));","stdin":"","call":"System.out.println(fileName(\"music/jazz/2024/live/track01.mp3\"));\n","expect":"track01.mp3","hidden":true},{"name":"System.out.println(fileName(\"a/b\"));","stdin":"","call":"System.out.println(fileName(\"a/b\"));\n","expect":"b","hidden":true}],"require":[{"pattern":"\\.split\\s*\\(","message":"Cut the path into parts with `split`."}],"forbid":[]},{"task":"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:\n\n```\nPNG\n```\n","kind":"code","seed":"import java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        String phrase = scanner.nextLine();\n\n    }\n}\n","solution":"import java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        String phrase = scanner.nextLine();\n        String acronym = \"\";\n        for (String word : phrase.split(\" \")) {\n            acronym += word.charAt(0);\n        }\n        System.out.println(acronym.toUpperCase());\n    }\n}\n","hints":["Split the phrase at the spaces and loop over the words. Start from `String acronym = \"\";`.","Add each word's first letter with `acronym += word.charAt(0);`, and print `acronym.toUpperCase()` after the loop."],"tests":[{"name":"Test 1","stdin":"portable network graphics\n","expect":"PNG","hidden":false},{"name":"Test 2","stdin":"as soon as possible\n","expect":"ASAP","hidden":true},{"name":"Test 3","stdin":"Frequently Asked Questions\n","expect":"FAQ","hidden":true},{"name":"Test 4","stdin":"hello\n","expect":"H","hidden":true}],"require":[{"pattern":"\\.split\\s*\\(","message":"Cut the phrase into words with `split`."},{"pattern":"\\.charAt\\s*\\(","message":"Take the first letter of each word with `charAt(0)`."}],"forbid":[]}]}