This post will explore several ways to split the string in Java using a given delimiter.

1. Using String.split() method

The standard solution is to use the split() method provided by the String class. It takes the delimiting regular expression as an argument and returns an array of strings.

Please note that we need to escape a few characters in some cases, which happens to be a special character in the regex. For example, a dot(.), pipe(|) or dollar($).

Download  Run Code

Output:

[A, B, C]

2. Using Guava’s Splitter Class

Another good alternative is to use the Splitter class from the Guava library, as shown below. Note that this returns an Iterable instead of an array of strings.

Download Code

Output:

[A, B, C]

3. Using splitAsStream() method

From Java 8 onwards, we can also use the splitAsStream() method, which returns the stream of strings computed by splitting the input around matches of the given pattern.

Download  Run Code

Output:

[A, B, C]

4. Using Apache Commons Lang

We can also leverage the StringUtils.split() method of Apache Commons Lang library, which splits the string into an array using a given separator.

Download Code

5. Using StringTokenizer Class

The StringTokenizer is a legacy class that allows breaking a string into tokens using a set of delimiters. This solution is not recommended in the new code.

Download  Run Code

Output:

A
B
C

That’s all about splitting Java String using a given delimiter.