Start learning free

LESSON 62 OF 344 · STRINGS I

String Split in Java: Breaking Text into a String Array

Lesson Read the full explanation

In Java, you can split a string into an array of substrings using split(). It takes a regular expression as the delimiter:

s.split(regex)   // splits using a regex delimiter

Here are some examples:

String sentence = "hello world foo";
String[] words = sentence.split(" ");
// words == ["hello", "world", "foo"]

String csv = "a,b,c";
String[] parts = csv.split(",");
// parts == ["a", "b", "c"]

You can loop through the resulting array:

for (String w : words) {
    System.out.println(w);
}

Assignment
Follow the Coding Tutorial and split sentence into a String array!


Hint
Use sentence.split(" ") and assign the result to words.

STEP 1 OF 1
    Ctrl + Enter to check

    JAVA · STRINGS I

    String Split in Java, explained

    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:

    1. Declare a String[] named words below sentence. The result of split is an array of strings, so that is the variable's type.
    2. 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 words hello, world and foo.

    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, a and b. 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, then a. 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 gives a and b-c.
    • An empty pattern splits into characters. "abc".split("") gives a, b, c.
    • The original string is unchanged, since strings are immutable.

    Key takeaways

    • s.split(regex) returns a String[] 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.
    Keep going with JavaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free