Java String split()

The String split() method returns an array of split strings after the method splits the given string around matches of a given regular expression containing the delimiters.

The regular expression must be a valid pattern and remember to escape special characters if necessary.

String str = "A-B-C-D";

String[] strArray = str.split("-");	// [A, B, C, D]

1. String split() API

1.1. Syntax

The split() method is overloaded.

  • regex – the delimiting regular expression.
  • limit – controls the number of times the pattern is applied and therefore affects the length of the resulting array.
    • If the limit is positive then the pattern will be applied at most limit – 1 times. The result array’s length will be no greater than limit, and the array’s last entry will contain all input beyond the last matched delimiter.
    • If the limit is zero then result array can be of any size. The trailing empty strings will be discarded.
    • If the limit is negative then result array can be of any size.
public String[] split(String regex);

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

1.2. Throws PatternSyntaxException

Watch out that split() throws PatternSyntaxException if the regular expression’s syntax is invalid. In given example, "[" is invalid regular expression.

public class StringExample
{
    public static void main(String[] args)
    {
        String[] strArray = "hello world".split("[");
    }
}

Program output.

Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character class near index 0
[
^
	at java.util.regex.Pattern.error(Pattern.java:1955)
	at java.util.regex.Pattern.clazz(Pattern.java:2548)
	at java.util.regex.Pattern.sequence(Pattern.java:2063)
	at java.util.regex.Pattern.expr(Pattern.java:1996)
	at java.util.regex.Pattern.compile(Pattern.java:1696)
	at java.util.regex.Pattern.<init>(Pattern.java:1351)
	at java.util.regex.Pattern.compile(Pattern.java:1028)
	at java.lang.String.split(String.java:2367)
	at java.lang.String.split(String.java:2409)
	at com.StringExample.main(StringExample.java:9)

1.3. ‘null’ is Not Allowed

The method does not accept ‘null’ argument. It will throw NullPointerException in case the method argument is null.

Exception in thread "main" java.lang.NullPointerException
	at java.lang.String.split(String.java:2324)
	at com.StringExample.main(StringExample.java:11)

2. Demo

Example 1: Split a String into an Array with the Given Delimiter

Java program to split a string based on a given token. In the given example, I am splitting string for delimiter hyphen "-".

public class StringExample
{
    public static void main(String[] args)
    {
        String str = "how to do-in-java-provides-java-tutorials";

        String[] strArray = str.split("-");

        System.out.println(Arrays.toString(strArray));
    }
}

Program output.

[how to do, in, java, provides, java, tutorials]

Example 2: Split String by Whitespace

Java program to split a string by space using the delimiter "\\s".

To split by all white space characters (spaces, tabs etc) use the delimiter “\\s+“.

public class StringExample
{
    public static void main(String[] args)
    {
        String str = "how to do in java provides java tutorials";

        String[] strArray = str.split("\\s");

        System.out.println(Arrays.toString(strArray));
    }
}

Program output.

[how, to, do, in, java, provides, java, tutorials]

Example 3: Split String by Comma

Java program to split a string by comma.

public class StringExample
{
    public static void main(String[] args)
    {
        String str = "A,B,C,D";

        String[] strArray = str.split(",");

        System.out.println(Arrays.toString(strArray));
    }
}

Program output.

[A,B,C,D]

Example 4: Split String by Multiple Delimiters

Java program to split a string with multiple delimiters. Use regex OR operator '|' symbol between multiple delimiters.

In the given example, I am splitting the string with two delimiters hyphen and dot.

public class StringExample
{
    public static void main(String[] args)
    {
        String str = "how-to-do-in-java. provides-java-tutorials.";

        String[] strArray = str.split("-|\\.");

        System.out.println(Arrays.toString(strArray));
    }
}

Program output.

[how, to, do, in, java, provides, java, tutorials]

3. String split(regex, limit) Example

This version of the method also splits the string, but the maximum number of tokens can not exceed limit argument. After the method has found given the number of tokens, the rest of the unsplitted string is returned as the last token, even if it may contain the delimiters.

Below given is a Java program to split a string by space in such as the way the maximum number of tokens can not exceed 5.

public class StringExample
{
    public static void main(String[] args)
    {
        String str = "how to do in java provides java tutorials";

        String[] strArray = str.split("\\s", 5);

        System.out.println(strArray.length);	//5
        System.out.println(Arrays.toString(strArray));
    }
}

Program output.

5

[how, to, do, in, java provides java tutorials]

Happy Learning !!

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial