Saturday, 12 September 2015

Java String split

Java String split

The java string split() method splits this string against given regular expression and returns a char array.

Signature

There are two signature for split() method in java string.
  1. public String split(String regex)  
  2. and,  
  3. public String split(String regex, int limit)  

Parameter

regex : regular expression to be applied on string.
limit : limit for the number of strings in array. If it is zero, it will returns all the strings matching regex.

Returns

array of strings

Throws

PatternSyntaxException if pattern for regular expression is invalid

Since

1.4

Java String split() method example

The given example returns total number of words in a string excluding space only. It also includes special characters.
  1. public class SplitExample{  
  2. public static void main(String args[]){  
  3. String s1="java string split method by javatpoint";  
  4. String[] words=s1.split("\\s");//splits the string based on string  
  5. //using java foreach loop to print elements of string array  
  6. for(String w:words){  
  7. System.out.println(w);  
  8. }  
  9. }}  
Output
java
string
split
method
by
javatpoint

Java String split() method with regex and length example

  1. public class SplitExample2{  
  2. public static void main(String args[]){  
  3. String s1="welcome to split world";  
  4. System.out.println("returning words:");  
  5. for(String w:s1.split("\\s",0)){  
  6. System.out.println(w);  
  7. }  
  8. System.out.println("returning words:");  
  9. for(String w:s1.split("\\s",1)){  
  10. System.out.println(w);  
  11. }  
  12. System.out.println("returning words:");  
  13. for(String w:s1.split("\\s",2)){  
  14. System.out.println(w);  
  15. }  
  16.   
  17. }}  
Output
returning words:
welcome 
to 
split 
world
returning words:
welcome to split world
returning words:
welcome 
to split world

No comments:

Post a Comment