Java String split()
There are situation where strings contain multiple pieces of information , then we will need to split the string to extract the individual pieces. Strings in Java can be split using the split() method of the String class. Syantax
public String[] split(String regex)
regex : regular expression to be applied on string.
Returns: array of strings
Example
class TestClass{
public static void main (String[] args){
String str = "007-034456-0076";
String[] parts = str.split("-");
for (String x : parts)
System.out.println(x);
}
}
Output
007
034456
0076
Java String split() is based on regex expression, a special attention is needed with some characters which have a special meaning in a regex expression.
Spliting string with limit
Syntax
public String split(String regex, int limit)
You can set a limit the output strings.
Example
class TestClass{
public static void main (String[] args){
String str = "1111-2222-3333-4444-5555";
String[] parts = str.split("-",2);
for (String x : parts)
System.out.println(x);
}
}
Output
1111
2222-3333-4444-5555
There are situation that several characters being used as delimiters.
Example
class TestClass{
public static void main (String[] args){
String str = "(a+b)-c/d";
String[] parts = str.split("[()+-/]+");
for (String x : parts)
System.out.println(x);
}
}
Output
a
b
c
d
How to split a String by space
Java String.split() method is based upon regular expressions. So provide "\\s+" as split parameter.
Example
class TestClass{
public static void main (String[] args){
String str = "Java String Tutorial";
String[] parts = str.split("\\s+");
for (String x : parts)
System.out.println(x);
}
}
Output
Java
String
Tutorial
Related Topics
- How to Get the Length of a String
- Java String charAt() Method
- String indexOf() method
- Java String replace()
- Java String contains()
- String Comparison in Java
- Java String substring()
- Java String concat() Method
- Convert String to int
- Java StringBuilder Class
- StringTokenizer in Java
- How to convert int to String in Java?