How to split a string with delimiter in java

Many times you get multiple values from the server or a web service and all the values are separated by a character or a pattern. Example, details of an employee received from a web server are 123@John@USA where the values separated by @ symbol are the id, Name and country of the employee respectively.
Now in order to display or get each of these values separately, you need some mechanism. That is where, split method becomes useful.


split method in java
split method belongs to java.lang.String class. It takes a pattern or a string as argument and breaks the string, on which it is invoked, into parts based on the supplied pattern(or a regular expression).
split method separates the source string into parts and where every part is created by removing the supplied pattern or regular expression from the source string. It returns an array whose elements are created by splitting the string on regular expression.
Thus, "123@John@USA".split("@") will return an array whose elements will be 123, John and USA.
Remember that the regular expression on which the string is split is not present in the resulting array. Below are some usage examples of split method.

"absbdscdsef".split("s") will return an array with elements “ab”, “bd”, “cd” and “ef”
"123#451#675*#65".split("#") will return an array of “123”, “451”, “675” and “#65”
"d3&*g3&*W4&*kli".split("&*") will return an array of “d3”, “g3”, “W4” and “kli”

Also note that the regular expression can be a string of a single character or multiple characters.
split method types
java.lang.String class contains two overloaded versions of split method as explained below.
1. split(String pattern) : This method takes a string pattern as an argument and divides the source string based on that pattern. This method is the same as demonstrated above.
2. split(String pattern, int limit) : This method takes two arguments where the first argument is the string pattern based on which the string will be partitioned and second argument is an integer which determines the number of times, split operation will be applied on the source string.
Limit can have different range of values as follows
Positive: If the limit is greater than zero, then the split operation is applied for (limit – 1) times. Thus, in this case the length of result array will never be greater than the limit.
Zero: If the limit is zero, then the split operation will be applied as long as the pattern is present in the source string.
When the limit is zero, then the trailing empty strings will be removed from the result array. This is the same as the single argument split method.
Negative: When the limit is less than zero, then the split operation will be applied as long as the pattern is present in the source string as in the previous option but here trailing empty strings will also be present in the resultant array.


Below examples will clarify the meaning of limit values in split. It is also an example of split a string by dot. Notice the trailing dot(.) in the source string in the examples.

Method Result Array Elements Explanation
String str = "www.codippa.com.";
str.split("\\.", 2);
“www”, “codippa.com.” split operation will be applied for 1 time, therefore only 2 elements will be present in the array.
Total split operations = 1
String str = "www.codippa.com.";
str.split("\\.", -1);
“www”, “codippa”, “com”, “” split will be applied till the pattern(.) is present in the string.
Notice that the last array element is an empty string.
Total split operations = 4
String str = "www.codippa.com.";
str.split("\\.", 0);
“www”, “codippa”, “com” split will be applied till the pattern(.) is present in the string.
Notice that the empty string for the last split operation is removed from the array.
Total split operations = 4
String str = "www.codippa.com.";
str.split("\\.", 3);
“www”, “codippa”, “com.” Total split operations = 2
Notice the dot(.) in the last array element.
String str = "www.codippa.com.";
str.split("\\.");
“www”, “codippa”, “com” Note that the trailing empty elements are removed

Since the dot is a special character in regular expression, it is required to escape this character, that is why it is preceded with double back slashes(\\).

For split to work correctly on any of the regular expression special characters such as ., ^, *, (, ), [, ] and |(pipe), precede them with double back slashes such as "Hi*there".split("\\*")


split method in java example program
Now its time to understand the usage of split method by example programs as follows.

public class SplitDemo {
   public static void main(String[] args) {
	// source string
	String str = "Hi!there!Welcome!to!Java";
	// split the string on a pattern and assign result to array
	String[] arr = str.split("!");
	// iterate over the array
	for (String item : arr) {
	   // print the string
	   System.out.println(item);
	}
   }
}

Above code when executed prints the below output

Hi
there
Welcome
to
Java

Output should be self-explanatory by now.

split string by space example
There are two ways to split a string with a space as pattern.
1. Provide a space(” “) as the pattern to the split method.
2. Supply regular expression equivalent to a space which is \\s as the pattern to split method.
Both the approaches are demonstrated below.

public class SplitSpaceDemo {
   public static void main(String[] args) {
	// source string
	String str = "Hi there Welcome";
	// split the string on space
	String[] arr = str.split(" ");
	// iterate over the array
	for (String item : arr) {
	   // print the string
	   System.out.println(item);
	}
        // split the string on regular expression
	[] arr = str.split("\\s");
	// iterate over the array
	for (String item : arr) {
	   // print the string
	   System.out.println(item);
	}
   }
}

Above program produces below output

Hi
there
Welcome
Hi
there
Welcome


Hope this article must have clarified the concept of split method in java.lang.String class and its usage. Hit the clap below if you liked the post.

0

Mark Your Impression

Close Menu