Thursday, May 28, 2009

Know how to use split() method of String class in Java...!!!

Java 1.4 introduced a new method called split() in order to simplify a task of breaking string into substrings or tokens. It takes regular expression as parameter and breaks the string into substrings by matching this regular exp within the string.

Two methods are used for this purpose

1) split(String exp): In this exp is the regular expression and it will return an array of strings.

example:
String names= "Nagpur,Pune,Mumbai,Delhi";
String names[]=names.split(",");

O/P : When you iterate that array the output will be
Nagpur
Pune
Mumbai
Delhi

2) split(String exp, int max)
: Now this method has two parameters
where exp- regular exp
max- number of times to apply that pattern.

No comments:

Post a Comment