Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

String.split()

Splits a string into an array of parts by a separator.

Available since: Java 1.4

Syntax

public String[] split(String regex)

Parameters

ParameterTypeDescription
regexStringThe separator, as a regular expression. There is a version with a second limit argument.

Return value

String[]An array of strings, String[].

Examples

Splitting by a comma:

void main() {
    String csv = "Anna,Oleg,Maria";
    String[] names = csv.split(",");
    IO.println(names.length);
    IO.println(names[1]);
}

Output:

3
Oleg

Words separated by any number of spaces:

void main() {
    String text = "one   two three";
    for (String word : text.split("\\s+")) {
        IO.println(word);
    }
}

Output:

one
two
three

A dot must be escaped — it is a special regex character:

void main() {
    String ip = "192.168.0.1";
    IO.println(ip.split(".").length);
    IO.println(ip.split("\\.").length);
}

Output:

0
4

Notes

Empty strings at the end are dropped: "a,b,,".split(",") gives 2 elements. To keep them, pass -1 as the second argument: split(",", -1).

Escape the special characters ., |, +, *, ?, (, $ with two backslashes or wrap the separator in Pattern.quote().

See also

  • String.join() — Joins strings with a separator.
  • 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.
  • Arrays.toString() — Returns the contents of an array as a string like [1, 2, 3].

Related recipes

In the tutorial

  • String methods — The main String methods in Java: searching, substring, changing case, strip, replace, split, join, repeat and string checks.

Thanks for reading!

Donate to the site — we work hard for you.