What is split() string in Java?
StrSplit()
method allows you to break a string based on specific Java string delimiter. Mostly the Java string split attribute will be a space or a comma(,) with which you want to break or split the string
Syntax
public String split(String regex)
public String split(String regex, int limit)
Parameter
-
Regex: The regular expression in Java split is applied to the text/string
-
Limit: A limit in Java string split is a maximum number of values in the array. If it is omitted or zero, it will return all the strings matching a regex.
How to Split a String in Java with Delimiter
Below example shows how to split string in Java with delimiter:
Suppose we have a string variable named strMain
formed of a few words like Alpha, Beta, Gamma, Delta, Sigma – all separated by the comma (,).
Here if we want all individual strings, the best possible pattern would be to split it based on the comma. So we will get five separate strings as follows:
-
Alpha
-
Beta
-
Gamma
-
Delta
-
Sigma
Use the string split in Java method against the string that needs to be divided and provide the separator as an argument.
In this Java split string by delimiter case, the separator is a comma (,) and the result of the Java split string by comma operation will give you an array split.
class StrSplit{
public static void main(String []args){
String strMain = "Alpha, Beta, Delta, Gamma, Sigma";
String[] arrSplit = strMain.split(", ");
for (int i=0; i < arrSplit.length; i++)
{
System.out.println(arrSplit[i]);
}
}
}
The loop in the code just prints each Java split string to array after the split function in Java, as shown below-
Output:
Alpha
Beta
Delta
Gamma
Sigma
Example: Java String split() method with regex and length
Consider a situation, wherein you require only the first ‘n’ elements after the split function in Java but want the rest of the string to remain as it is. An output something like this-
-
Alpha
-
Beta
-
Delta, Gamma, Sigma
This can be achieved by passing another argument along with the split() string in Java operation, and that will be the limit of strings required.
Consider the following code of split method in Java –
class StrSplit2{
public static void main(String []args){
String strMain = "Alpha, Beta, Delta, Gamma, Sigma";
String[] arrSplit_2 = strMain.split(", ", 3);
for (int i=0; i < arrSplit_2.length; i++){
System.out.println(arrSplit_2[i]);
}
}
}
Output:
Alpha
Beta
Delta, Gamma, Sigma
How to Split a string in Java by Space
Consider a situation, wherein you want to split a string by space. Let’s consider an example here; we have a split string Java variable named strMain formed of a few words Welcome to Guru99.
public class StrSplit3{
public static void main(String args[]){
String strMain ="Welcome to Guru99";
String[] arrSplit_3 = strMain.split("\\s");
for (int i=0; i < arrSplit_3.length; i++){
System.out.println(arrSplit_3[i]);
}
}
}
Output:
Welcome
to
Guru99