Java provides the String.split() method to split a string into an array based on the given regular expression.

Here is an example:

String fruits = "Orange:Mango:Apple:Banana";

// split string into an array
String[] fruitsArray = fruits.split(":");

// print all array values
System.out.println(fruitsArray[0]);
System.out.println(fruitsArray[1]);
System.out.println(fruitsArray[2]);
System.out.println(fruitsArray[3]);

The above code will output the following:

Orange
Mango
Apple
Banana

String.split() Syntax

The String class provides two variants of split() to split a string in Java:

public String[] split(String regex)
public String[] split(String regex, int limit)

Parameters

The split() method accepts at most two parameters:

  • regex — The first parameter is the regular expression string that is used to break the string into an array. If no matching string is found in the given string, the complete string is returned as a single value array.
  • limit — The second optional parameter is used to limit the number of results returned. You can use this parameter to force the string to be split into a specific number of strings.

Return value

On a successful split, an array of strings computed by splitting the given string is returned. If the regular expression string is not valid, a PatternSyntaxException is thrown.

String Split Examples

1. Split String by Period / Dot

Since the period or dot (.) is treated as a special character in regular expressions, you must escape it either with a double backslash (\\) or use the Pattern.quote() method:

String animals = "Lion.Cheetah.Bunny";

// split string into an array
String[] tokens = animals.split("\\.");

// alternative
// String[] tokens = animals.split(Pattern.quote("."));

// print all array values
System.out.println(tokens[0]);
System.out.println(tokens[1]);
System.out.println(tokens[2]);

Here is the output:

Lion
Cheetah
Bunny

2. Split String by New Line

To split a string by a new line in Java, you can use \\r?\\n as a regular expression, as shown below:

String str = "I\nam\r\nAtta!";

// split string into an array
String[] tokens = str.split("\\r?\\n");

// print all array values
System.out.println(tokens[0]);
System.out.println(tokens[1]);
System.out.println(tokens[2]);

You should see the following output:

I
am
Atta!

3. String Split with Limited Results

The following example shows how you can limit the resultant array size by passing a limit parameter to split():

String str = "Atlanta (ATL), GA, USA";

// split string into an array
String[] tokens = str.split(",", 2);

// print all array values
System.out.println(tokens[0]);
System.out.println(tokens[1]);

The above code snippet will print the following:

Atlanta (ATL)
 GA, USA

Read Next: Convert a comma-separated string to a list in Java

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.