Java String split() method
Java String split() method split current String against given regular expression and returns a char array.
Syntax:
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:
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:
Welcome to the Tutorial and example
Java String split() method with regex and length example 2
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:
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
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:
Returning words: Tu orialand Example Split array length: 2
Java String split() method with regex and limit example 4
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:
Tutorial And Example
Java String split() method example 5
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:
Tutorial And Example