

Splitting String in Java – Examples and Tips
String splitting is one of the string manipulation techniques which breaks a given string into tokens using predefined separators or delimiters. Developers split strings almost daily and it is also used as a base for many not really trivial interview questions.
Below are listed some basic examples on how we split a string in Java together with an additional description for each approach. What we choose in the end may be based on requirements or which libraries we currently use in the project or simply a preference and code style.
String Split Method
Description
String class offers a split method, which is suitable for some scenarios. The method is simply splitting the string by using a delimiter passed as a parameter. The parameter can be a regular expression or a simple character. Method signature can be:
1 |
String[] split(String regex) |
or
1 |
String[] split(String regex, int limit) |
There is also an option to add a limit that can be negative, positive, or equal to 0.
- If the limit has a positive value, the string will be split at the most limit – 1 time, and what is left after the third split will be attached at the end of the last string result array element.
- If the limit has a negative value, the string will be split like it would be without passing the limit – as many times as possible – but trailing spaces will be added as part of the result if any. The actual negative value will not be taken into consideration.
- If the limit is equal to 0, the string will be split as it would be without passing the limit.
Examples
1. Split With Simple Character:
1 2 3 4 5 6 |
tring wordsForSplitting = "test-splitting-string"; String[] arrayOfWords = wordsForSplitting.split("-"); // would have the same result if wordsForSplitting.split("-", 0) is used System.out.println(arrayOfWords[0]); System.out.println(arrayOfWords[1]); System.out.println(arrayOfWords[2]); |
Output:
1 2 3 |
test splitting string |
2. Split with a Regular Expression:
1 2 3 4 5 6 |
String sentenceManyDelimiters = "Split sentence when you have : , questions marks ? or email @."; String[] arrayOfWords = sentenceManyDelimiters.split("[,?.@:]+"); for (String word : arrayOfWords) { System.out.println(word); } |
Output:
1 2 3 4 5 6 7 8 9 |
Split sentence when you have questions marks or email |
3. Split with positive limit:
1 2 3 4 5 6 |
String wordsForSplitting = "test-splitting-string--"; String[] arrayOfWords = wordsForSplitting.split("-", 2); for (String word : arrayOfWords) { System.out.println(word); } |
Output:
1 2 |
test splitting-string-- |
4. Split with negative limit:
1 2 3 4 5 |
String wordsForSplitting = "test-splitting-string--"; String[] arrayOfWords = wordsForSplitting.split("-", -15); for (String word : arrayOfWords) { System.out.println(word); } |
Output:
1 2 3 4 5 6 |
test splitting string "" "" "" |
* All the empty strings are shown as “”
5. Split with Stream API
1 2 3 4 5 6 7 8 |
String sentanceCommas = "Split sentence when you have, commas, and more .."; List<String> stringList = Stream.of(sentanceCommas.split(",")) .map (elem -> new String(elem)) .collect(Collectors.toList()); for (String obj : stringList) { System.out.println(obj); } |
Output:
1 2 3 |
Split sentence when you have commas and more... |
Pattern compile method
Description
There is an option to use Pattern class which is Java implementation for regular expressions. After an expression is compiled, we can match multiple strings using the regular expression that builds the pattern. The advantage of this approach is that in this way, we can add more constraints on the input, for example, ensuring that we match only words that are split with ‘-’.
Matcher object group method can access each of the subsequent matches. The count of the matches can be retrieved using method groupCount.
Capturing each matched group can be done using direct access to each of the groups, as shown in the example below. Group 0 is used to represent the entire expression.
Examples
1 2 3 4 5 6 7 8 9 |
final Pattern wordsRe = Pattern.compile("(\\w+)-(\\w+)"); String wordsForSplitting = "test-splitting-string--"; Matcher m = wordsRe.matcher(wordsForSplitting); if (m.matches()) { System.out.println(m.group(0)); System.out.println(m.group(1)); System.out.println(m.group(2)); } |
Output:
1 2 3 |
test-splitting test splitting |
Apache Commons StringUtils Method
Description
If we decide to use Apache Commons Lang library, a null-safe method split from StringUtils will do the job. If no separator is specified, it splits the string using the default one, which is space (“ ”). It also takes care of the leading and trailing spaces. In the documentation, there is a full description of all methods that have different usage, like splitByWholeSeparator, which splits the content using a full “whole” string.
Examples
1. StringUtils Split Method
1 2 3 4 5 |
String[] stringArray = StringUtils.split("Split sentence when you have spaces "); for (String obj : stringArray ) { System.out.println(obj); } |
Output:
1 2 3 4 5 6 |
Split sentence when you have spaces |
2. StringUtils splitByWholeSeparator Method
1 2 3 4 5 |
String[] stringArray = StringUtils.splitByWholeSpearator("Split sentence when you have , comma ,; colon", ",;"); for (String obj : stringArray ) { System.out.println(obj); } |
Output:
1 2 |
Split sentence when you have, comma colon |
Google Guava Splitter Class
Description
Google Guava provides a Splitter class that has different methods for handling splitting operations using a separator. This separator can be specified as a single character, fixed string, regular expression. Multiple helper methods can pamper the result list.
Example
1 2 3 4 |
List<String> resultList = Splitter.on('-') .trimResults() .omitEmptyStrings() .splitToList("--test-splitting-string"); |
Output:
1 2 3 |
test splitting string |