Java string split

In this article, we will take a look at how to split or divide a string based on a delimiter or separator and a regular expression in java.

Example, suppose the 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.

Java string split() method
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 quick 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() methods
java.lang.String class contains two overloaded versions of split() method as explained below.

1. split(String pattern)
This method takes a string pattern or regex 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
A. Pattern based on which the string will be partitioned, and
B. 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
A. 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.

B. 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.

C. 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("\\*")

Java string split() example
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.

Java string split 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
      String[] 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

Similar to the examples above, you can also split a string by comma, dot or any other character in java.
Java string split by comma
Below is an example of splitting a string by comma.

String s = "orange,apple,banana";
String[] fruits = s.split(",");
String fruitNames = Arrays.toString(fruits);

This prints

[orange, apple, banana]

Java split string by regex
First argument to split() method is a pattern string.
It may be a string that is contained in the source string or it may also be a regular expression. If it is a regular expression, then it is matched and the string is then split based on its value.

Example, \\d is a regular expression which matches integer values. Below program matches this in the string to perform split operation.

String s = "orange1apple2banana";
String[] fruits = s.split("\\d");
String fruitNames = Arrays.toString(fruits);

Result is

[orange, apple, banana]

Hope this article must have clarified the concept of split() method in java.lang.String class and its usage.

Leave a Reply