Java – Split a String with Specific Character
To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.
The syntax to split string by space is
</>
Copy
String.split(x)
where x
is specific character by which we would like to split this string. Please note that we have to pass the character as string in double quotes.
Split String by Comma
In the following program, we have taken a string and split it by comma.
Java Program
</>
Copy
public class Example {
public static void main(String[] args){
String str = "abc,defg,hi,jklm";
String parts[] = str.split(",");
for(String part: parts) {
System.out.println(part);
}
}
}
Output
abc
defg
hi
jklm
Split String by Alphabet
In the following program, we have taken a string and split it by the character m
.
Java Program
</>
Copy
public class Example {
public static void main(String[] args){
String str = "abcmdefgmhimjkl";
String parts[] = str.split("m");
for(String part: parts) {
System.out.println(part);
}
}
}
Output
abc
defg
hi
jkl
Conclusion
In this Java Tutorial, we learned how to split a string by specific character, using String.split() method.