Split a string in Java using dot, dollar or question mark as a delimiter

In this post, we will explore different ways to split a string in Java using dot (.), pipe (|) or dollar ($) or question mark (?) as a delimiter.

 

1. String.split()

The standard solution is to use split() method provided by the String class. It takes a regular expression as delimiter and returns a String array.

 

Download   Run Code

 
If we run the above code, it doesn’t work as expected. This is because the split() method takes a regular expression, and dot is special character which matches any character in regex. We can avoid this behavior by creating a regex which will represent a dot. There are several ways to do this which are covered below in detail:

 

1.1. Using an escape character

We can make above code work by escaping the dot character. An escape character invokes an alternative interpretation on following characters of a string. In Java, the \ (backslash) is used to escape special characters. Note that Java follows the two backslash escape styles.

 

Download   Run Code

 

1.2. Wrapping dot between \Q and \E

Another plausible way of escaping is using \Q to backslash all subsequent special characters and \E to end the expression.

 

Download   Run Code

 

1.3. Character classes

We can also use Character classes in Java for escaping the dot (.) as shown below:

 

Download   Run Code

 

1.4. Pattern.quote()

Another good alternative is to use Pattern.quote() which returns a literal pattern String for the specified String.

 

Download   Run Code

 

2. Guava’s Splitter Class

We can use Splitter class from Guava library as shown below which returns an Iterable.

 

Download   Run Code

 

3. Apache Commons Lang

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

 

 

4. StringTokenizer

The StringTokenizer is a legacy class which allows to break a string into tokens using a delimiter as shown below:

 

Download   Run Code

 

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of