Saturday 21 June 2014

split (String regex, int limit)

public String[] split(String regex, int limit)
Splits this string around matches of the given regular expression.

The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.

Limit Description
Greater Than zero If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.
Less Than zero If limit n is non-positive then the pattern will be applied as many times as possible and the array can have any length.
Equal to zero
If limit n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.



class StringSplit1{
 public static void main(String args[]){
  String s1 = "boo:and:foo";
  String s2[];

  System.out.println("s1 = " + s1);
  
  System.out.println("Spliting 2 times");
  s2 = s1.split(":", 2);
  for(int j=0; j<s2.length; j++){
   System.out.print(s2[j]+",");
  }
  
  System.out.println("\nSpliting 3 times");
  s2 = s1.split(":", 3);
  for(int j=0; j<s2.length; j++){
   System.out.print(s2[j]+",");
  }
  
  System.out.println("\nSpliting 0 times");
  s2 = s1.split(":", 0);
  for(int j=0; j<s2.length; j++){
   System.out.print(s2[j]+",");
  }
  
  System.out.println("\nSpliting -1 times");
  s2 = s1.split(":", -1);
  for(int j=0; j<s2.length; j++){
   System.out.print(s2[j]+",");
  }
 }
}

Output
s1 = boo:and:foo
Spliting 2 times
boo,and:foo,
Spliting 3 times
boo,and,foo,
Spliting 0 times
boo,and,foo,
Spliting -1 times
boo,and,foo,







Prevoius                                                 Next                                                 Home

No comments:

Post a Comment