Java String split() method split current String against given regular expression and returns a char array.
Syntax:
1 2 3 4 |
public String split(String regex) public String split(String regex, int limit) |
Parameters:
regex : it is a regular expression to be applied on String.
limit : it is limit for the number of Strings in array. If it is zero , it will return all String matching regex.
Returns:
array of Strings
Throws:
PatternSyntaxException if pattern for regex is invalid.
Java String split() method 1 example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class JavaStringSplitEx1 { public static void main(String args[]) { String s1="Welcome to the Tutorial and example"; String[] words=s1.split("\\s");//splits the string based on whitespace //using java foreach loop to print elements of string array for(String w:words){ System.out.println(w); } } } |
Output:
1 2 3 4 5 6 7 8 |
Welcome to the Tutorial and example |
Java String split() method with regex and length example 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public class JavaStringSplitEx2 { public static void main(String args[]) { String s1="welcome to tutorialsandexample world"; System.out.println("returning words:"); for(String w:s1.split("\\s",0)){ System.out.println(w); } System.out.println(""); System.out.println("returning words:"); for(String w:s1.split("\\s",1)){ System.out.println(w); } System.out.println(""); System.out.println("returning words:"); for(String w:s1.split("\\s",2)){ System.out.println(w); } } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 |
returning words: welcome to tutorialsandexample world returning words: welcome to tutorialsandexample world returning words: welcome to tutorialsandexample world |
Java String split() method with regex and length example 3
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class JavaStringSplitEx3 { public static void main(String[] args) { String str = "Tutorialand Example"; System.out.println("Returning words:"); String[] arr = str.split("t", 0); for (String w : arr) { System.out.println(w); } System.out.println("Split array length: "+arr.length); } } |
Output:
1 2 3 4 5 6 |
Returning words: Tu orialand Example Split array length: 2 |
Java String split() method with regex and limit example 4
1 2 3 4 5 6 7 8 9 10 11 12 |
public class JavaStringSplitEx4 { public static void main(String args[]) { String str = "Tutorial&&And&&Example"; String [] arrOfStr = str.split("&", 5); for (String a : arrOfStr) System.out.println(a); } } |
Output:
1 2 3 4 5 |
Tutorial And Example |
Java String split() method example 5
1 2 3 4 5 6 7 8 9 10 11 12 |
public class JavaStringSplitEx5 { public static void main(String args[]) { String str = "Tutorial&&And&&Example"; String [] arrOfStr = str.split("&",-2); for (String a : arrOfStr) System.out.println(a); } } |
Output:
1 2 3 4 5 |
Tutorial And Example |