How to Split String in Java with Example
Here you will learn how to split string in java.
We can split string in Java using split() method of java.lang.String class. It takes a regular expression as an argument and returns an array of strings.
Syntax:
1 |
public String[] split(String regex) |
Split String in Java Example
Below program will split the string by space.
1 2 3 4 5 6 7 8 9 10 |
public class SplitStringJava { public static void main(String...s){ String str = "I Love Java Programming"; String strArray[] = str.split("\\s"); //split by space for(int i=0;i<strArray.length;++i){ System.out.println(strArray[i]); } } } |
Output
I
Love
Java
Programming
There are few special characters like ., ?, |, +, etc. and some escape characters like \n, \t, \b, etc. that must be escaped before using as a regular expression in split() method. We can escape them by using two backslash characters i.e. \\.
For example if you want to split the string by + character then you have to use \\+ as a regular expression in split() method.
Java String Split with Length
You can split a string by regular expression along with length using another variant of split() method.
Syntax:
1 |
public String[] split(String regex, int length) |
Example
1 2 3 4 5 6 7 8 9 10 |
public class SplitStringJava { public static void main(String...s){ String str = "I Love Java Programming"; String strArray[] = str.split("\\s", 2); for(int i=0;i<strArray.length;++i){ System.out.println(strArray[i]); } } } |
Output
I
Love Java Programming
As you can see in above example that the string is split into 2 parts because we have used length as 2.
Comment below If you found anything incorrect or have doubts related to above Java split string tutorial.