Split the string in Java using given delimiter

In this post, we will explore several ways to split the string in Java using given delimiter.

 

1. String.split()

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

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

 

Download   Run Code

Output:

[A, B, C]

 

2. Guava’s Splitter Class

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

 

Download   Run Code

Output:

[A, B, C]

 

3. Java 8 – splitAsStream()

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

 

Download   Run Code

Output:

[A, B, C]

 

4. Apache Commons StringUtils

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

 

 

5. StringTokenizer

The StringTokenizer is a legacy class which allows to break a string into tokens using a set of delimiters. This solution is not recommended in new code.

 

Download   Run Code

Output:

A
B
C

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of