Java String split method is used for splitting a String into substrings based on the given delimiter or regular expression.
For example:
Input String: chaitanya@singh Regular Expression: @ Output Substrings: {"chaitanya", "singh"}
Java String Split Method
We have two variants of split()
method in String class.
1. String[] split(String regex)
: It returns an array of strings after splitting an input String based on the delimiting regular expression.
2. String[] split(String regex, int limit)
: This method is used when you want to limit the number of substrings. The only difference between this variant and above variant is that it limits the number of strings returned after split up. For example: split("anydelimiter", 3)
would return the array of only 3 strings even if there can be more than three substrings.
What if limit is entered as a negative number?
If the limit is negative then the returned string array would contain all the substrings including the trailing empty strings, however if the limit is zero then the returned string array would contains all the substrings excluding the trailing empty Strings.
It throws PatternSyntaxException
if the syntax of specified regular expression is not valid.
String split() method Example
If the limit is not defined:
public class JavaExample{ public static void main(String args[]){ // Input String String str = new String("17/09/2022"); System.out.println("Substrings of given string:"); /* Here we are using first variation of string split() method * which splits the string into substring based on the regular * expression, there is no limit on the substrings */ String strArr[]= str.split("/"); for (String temp: strArr){ System.out.println(temp); } } }
Output:
If positive limit is specified in the split() method: Here the limit is specified as 2 so the split method returns only two substrings.
public class JavaExample{ public static void main(String args[]){ // Input String String str = new String("17/09/2022"); System.out.println("Two Substrings of given string:"); //limit is set as 2 so it would return only two substrings String strArr[]= str.split("/", 2); for (String temp: strArr){ System.out.println(temp); } } }
Output:
If limit is specified as a negative number: As you can see that when the limit is negative, it included the trailing empty strings in the output. See the output screenshot below.
public class JavaExample{ public static void main(String args[]){ // Input String String str = new String("hello/hi/bye///"); System.out.println("Substrings when limit is negative:"); //negative limit String strArr[]= str.split("/", -1); int i=1; for (String temp: strArr){ System.out.print(i+". "); System.out.println(temp); i++; } } }
Output:
Limit is set to zero: This will exclude the trailing empty strings.
public class JavaExample{ public static void main(String args[]){ // Input String String str = new String("hello/hi/bye///"); System.out.println("Substrings when limit is Zero:"); //Zero limit String strArr[]= str.split("/", 0); int i=1; for (String temp: strArr){ System.out.print(i+". "); System.out.println(temp); i++; } } }
Output:
Difference between zero and negative limit in split() method:
- If the limit in split() is set to zero, it outputs all the substrings but exclude trailing empty strings if present.
- If the limit in split() is set to a negative number, it outputs all the substrings including the trailing empty strings if present.
Java String split() method with multiple delimiters
Let’s see how we can pass multiple delimiters while using split() method. In this example we are splitting input string based on multiple special characters.
public class JavaExample{ public static void main(String args[]){ String s = " ,ab;gh,bc;pq#kk$bb"; String[] str = s.split("[,;#$]"); //Total how many substrings? The array length System.out.println("Number of substrings: "+str.length); for (int i=0; i < str.length; i++) { System.out.println("Str["+i+"]:"+str[i]); } } }
Output:
Number of substrings: 7 Str[0]: Str[1]:ab Str[2]:gh Str[3]:bc Str[4]:pq Str[5]:kk Str[6]:bb
Lets practice few more examples:
Java Split String Examples
Example 1: Split string using word as delimiter
Here, a string (a word) is used as a delimiter in split()
method.
public class JavaExample { public static void main(String args[]) { String str = "helloxyzhixyzbye"; String[] arr = str.split("xyz"); for (String s : arr) System.out.println(s); } }
Output:
hello hi bye
Example 2: Split string by space
String[] strArray = str.split("\s+");
You can Split string by space using \s+
regex.
Input: "Text with spaces"; Output: ["Text", "with", "spaces"]
Example 3: Split string by pipe
String[] strArray = str.split("\|");
Split string by pipe ( | ) character using \|
regex.
Input: "Text1|Text2|Text3"; Output: ["Text1", "Text2", "Text3"]
Example 4: Split string by dot ( . )
String[] strArray = str.split("\.");
You can split string by dot ( . ) using \.
regex in split method.
Input: "Just.a.Simple.String"; Output: ["Just", "a", "Simple", "String"]
Example 5: Split string into array of characters
String[] strArray = str.split("(?!^)");
The ?! part in this regex is negative assertion, which it works like a not operator in the context of regular expression. The ^ is to match the beginning of the string. Together it matches any character that is not the beginning of the string, which means it splits the string on every character.
Input: "String"; Output: ["S", "t", "r", "i", "n", "g"]
Example 6: Split string by capital letters
String[] strArray = str.split("(?=\p{Lu})");
p{Lu}
is a shorthand for p{Uppercase Letter}
. This regex matches uppercase letter. The extra backslash is to escape the sequence. This regex split string by capital letters.
Input: "BeginnersBook.com"; Output: ["Beginners", "Book.com"]
Example 7: Split string by newline
String[] str = str.split(System.lineSeparator());
This is one of the best way to split string by newline as this is a system independent approach. The lineSeparator()
method returns the character sequence for the underlying system.
Example 8: Split string by comma
String[] strArray = str.split(",");
To split the string by comma, you can pass ,
special character in the split() method as shown above.
Khushboo bansal says
Is it right to say that 28 is present at array1[0], 12 at array1[1] and 2013 at array1[2]?
I am really confused right now.Please help.
Chaitanya Singh says
Thats correct.
Susan says
It would be helpful to include some examples that require use of the escape characters and which characters need them. It is one thing I was looking for. Once I realized that “|” needed “\\|”, my split worked like a champ.
Thanks for showing these using small code bits. It really does make a difference.
Chaitanya Singh says
I have added more examples.