Java string split example shows how to split string using the split method including by special characters like “.” (Dot), “|” (Pipe) etc. Also, how to limit the number of results returned by the split operation.
How to split a string in Java?
Use the split
method of the String class to split a string in Java.
1 |
public String[] split(String regex) |
This method splits a string and returns an array of strings parts.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.javacodeexamples.stringexamples; public class StringSplitExample { public static void main(String[] args) { //comma separated string String str = "Java,String,Split,Example"; //use split method to split a string by comma String[] parts = str.split(","); for(String part : parts){ System.out.println(part); } } } |
Output
1 2 3 4 |
Java String Split Example |
How to the limit number of string parts returned by the split method?
Use the overloaded split
method which accepts a limit parameter to limit the number of matches returned by the split
method.
1 |
public String[] split(String regex, int limit) |
The limit parameter denotes the number of times the pattern is applied on a string and thus the length of the resulting array.
1 2 3 4 5 6 7 8 |
String str = "Java,String,Split,Example"; //here, we want only two parts, so limit is 2 String[] parts = str.split(",", 2); for(String part : parts){ System.out.println(part); } |
Output
1 2 |
Java String,Split,Example |
Please note that the passing limit as 0 is the same as calling the split
method without the limit parameter.
How to split a string using special characters?
It is no different from splitting a string using normal delimiters. However, since the split
method accepts regular expression, if you want to split a string using a character that has a special meaning in the regular expression (called metacharacter), then those characters need to be escaped using the backslash.
Below given are the special metacharacters which need to be escaped.
a) Split a String by pipe “|”
1 2 3 4 5 6 7 |
String str = "String|split|by|pipe"; String[] parts = str.split("\\|"); for(String part : parts){ System.out.println(part); } |
Output
1 2 3 4 |
String split by pipe |
b) By caret “^”
1 2 |
String str = "String^split^by^caret"; String[] parts = str.split("\\^"); |
c) By dollar “$”
1 2 |
String str = "String$split$by$caret"; String[] parts = str.split("\\$"); |
d) By dot “.”
1 2 |
String str = "String.split.by.dot"; String[] parts = str.split("\\."); |
e) By a question mark “?”
1 2 |
String str = "String?split?by?question?mark"; String[] parts = str.split("\\?"); |
f) By asterisk “*”
1 2 |
String str = "String*split*by*asterisk"; String[] parts = str.split("\\*"); |
g) By plus “+”
1 2 |
String str = "String+split+by+plus"; String[] parts = str.split("\\+"); |
h) By opening parenthesis “(“
1 2 |
String str = "String(split(by(opening(parenthesis"; String[] parts = str.split("\\("); |
i) By closing parenthesis “)”
1 2 |
String str = "String(split(by(closing(parenthesis"; String[] parts = str.split("\\)"); |
j) By opening square bracket “[“
1 2 |
String str = "String[split[by[opening[square[bracket"; String[] parts = str.split("\\["); |
k) By opening curly bracket “{“
1 2 |
String str = "String{split{by{opening{curly{bracket"; String{] parts = str.split("\\{"); |
Note: Instead of escaping the special meaning characters using the double backslash, you can also use quote
method of Pattern class which does that automatically for you.
1 2 |
String str = "Java.String.Split"; String[] parts = str.split( Pattern.quote(".") ); |
How to split by a new line or line break?
If the string object contains multi-line text and you want to split a string by a new line or line break use the following code.
1 2 |
String str = "Your Text..."; String[] lines = str.split("\\r?\\n"); |
The above code takes care of both Unix and windows newline characters. Windows uses “\r\n” while Unix uses only “\n” as a line separator. Basically our pattern will split a string by zero or more “\r” followed by “\n” thus covering both Unix and Windows formats.
If you don’t want empty lines to be returned, change the pattern a bit as given below.
1 |
String[] lines = str.split("[\\r\\n]+"); |
How to split a string using Apache Commons library?
Apache Commons is a very useful library that provides a lots of useful functionalities that are not included in standard Java. The StringUtils
class provides a split method that can be used to split a String.
1 |
public static String[] split(String str, String separator) |
This method behaves like the split
method of String class except that the separator argument is not a regular expression. Hence there is no need to escape special metacharacters while using this method.
1 2 3 4 5 6 7 |
String str = "Your|Text|With|Pipe"; String[] parts = StringUtils.split(str, "|"); for(String part : parts){ System.out.println(part); } |
Will print
1 2 3 4 |
Your Text With Pipe |
How to return trailing empty strings with the split method?
Say for example you are trying to parse a CSV (comma separated values) file containing employee records. Here are the fields in the given sequence.
1 |
FirstName, LastName, Address 1, Address 2, City, Pin, Phone1, Phone2 |
Out of these fields, Phone1 and Phone2 are optional fields. That means you may or you may not get Phone1/Phone2 values for any particular record.
Now consider this example where Phone1 and Phone2 values are not present for a particular record.
1 2 3 4 5 6 7 8 |
String str = "John,Adams,95-Carlton Avenue,Jersey City,07094,,"; String[] parts = str.split(","); for(String part : parts){ System.out.println(part); } System.out.println("Done"); |
Output
1 2 3 4 5 6 |
John Adams 95-Carlton Avenue Jersey City 07094 Done |
The output is not what we expected. It should have printed the empty trailing string values for Phone1 and Phone2 fields even if they are empty. They are not printed because the split
method without the limit argument internally calls the split
method with the limit argument with limit value as 0. That, by default, does not return trailing empty string values.
To return trailing empty string values, use the split
method with limit argument having value as -1 as given below.
1 2 3 4 5 6 7 8 |
String str = "John,Adams,95-Carlton Avenue,Jersey City,07094,,"; String[] parts = str.split(",", -1); for(String part : parts){ System.out.println(part); } System.out.println("Done"); |
Will now print
1 2 3 4 5 6 7 8 |
John Adams 95-Carlton Avenue Jersey City 07094 Done |
This example is a part of the Java String tutorial.
Please let me know your views in the comments section below.