Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to split a string

Short answer

split() returns an array of parts:

void main() {
    String[] parts = "red,green,blue".split(",");
 
    IO.println(parts.length);
    IO.println(parts[1]);
}

Output:

3
green

Straight into a list

Wrap the array with List.of() or Arrays.asList() to print or process it as a collection:

void main() {
    var colors = List.of("red,green,blue".split(","));
    IO.println(colors);
}

Output:

[red, green, blue]

By whitespace

The argument of split() is a regular expression. \\s+ means "one or more whitespace characters":

void main() {
    String text = "  one   two\tthree ";
    var words = List.of(text.strip().split("\\s+"));
 
    IO.println(words);
}

Output:

[one, two, three]

A separator with spaces around it

The regular expression can eat the spaces around a comma right away:

void main() {
    var tags = List.of("java , spring,  sql".split("\\s*,\\s*"));
    IO.println(tags);
}

Output:

[java, spring, sql]

Limiting the number of parts

The second argument sets the maximum number of parts — the rest of the string goes into the last one:

void main() {
    String[] pair = "name=Anna=admin".split("=", 2);
 
    IO.println(pair[0]);
    IO.println(pair[1]);
}

Output:

name
Anna=admin

Common mistake

The dot, the vertical bar and some other characters are special in regular expressions. split(".") returns an empty array:

void main() {
    IO.println("192.168.0.1".split(".").length);
    IO.println("192.168.0.1".split("\\.").length);
    IO.println("a|b".split(Pattern.quote("|")).length);
}

Output:

0
4
2

Escape such characters with \\ or Pattern.quote().

Functions used in this recipe

  • String.split() — Splits a string into an array of parts by a separator.
  • Pattern.compile() — Compiles a regular expression into a Pattern object that can be reused many times.
  • String.lines() — Splits a string at line breaks and returns the lines as a stream.
  • String.strip() — Removes any Unicode whitespace from both ends of a string.

Thanks for reading!

Donate to the site — we work hard for you.