This post will discuss how to split a string on any whitespace character in Java.

A character is called a whitespace character in Java if and only if the Character.isWhitespace(char) method returns true. The most commonly used whitespace characters are ' ', '\t', '\n', '\r' and 'f'. There are several ways to split a string on whitespace characters:

1. Using String.split() method

The standard solution to split a string is using the split() method provided by the String class. It accepts a regular expression as a delimiter and returns a string array. To split on any whitespace character, you can use the predefined character class \s that represents a whitespace character.

Download  Run Code

Output:

[Hello, World]

 
Or using POSIX character class \p{Space}.

Download  Run Code

Output:

[Hello, World]

 
To group consecutive whitespaces as a single delimiter, you can use greedy quantifier \s+ where + represents one or more times.

Download  Run Code

Output:

[Hello, World]

 
If your string contains the leading or trailing spaces, trim the string before calling the split() method.

Download  Run Code

Output:

[Hello, World]

2. Using Pattern.compile() method

If the regular expression is frequently called, you might want to compile the regular expression for performance boost:

Download  Run Code

Output:

[Hello, World]

3. Using StringUtils class

We can also achieve this using the split() method from the StringUtils class provided by the Apache Commons library. This effectively handles leading and trailing spaces, and adjacent delimiters are also treated as one.

Download Code

Output:

[Hello, World]

4. Using StringTokenizer class

The StringTokenizer class allows breaking a string into tokens using the default delimiter set, which consists of the space character, the tab character, the newline character, the carriage-return character, and the form-feed character. The usage of this class is discouraged.

Download  Run Code

Output:

[Hello, World]

That’s all about splitting a string on any whitespace character in Java.