Java Reference
In-Depth Information
hi
hello
welcome
The
split
method is useful for parsing character sequences where the delimiter is
defi ned as a regular expression, as demonstrated by the following statements. See if you can
determine the output of this code:
String data = “3035551212,123 Main St.\tDenver,CO:50431”;
String [] results = data.split(“[;,:\\t]”);
for(String result : results) {
System.out.println(result);
}
The regular expression
[;,:\\t]
splits the
String
at every semicolon, comma, colon, or
tab. The output of the code is
3035551212
123 Main St.
Denver
CO
50431
Limiting the Results of the
split
Method
The
split
method also has an overloaded version that takes in an
int
that limits the
number of times the regular expression is applied to the
String
. If you specify a limit,
after the limit is reached the remaining characters are placed in the last element of the
String
array. For example, the following code invokes
split
with a limit of 3, so the
resulting array will not be larger than three elements. See if you can determine the output:
String s = “abc,def,g,hi,jklm,o”;
String [] array = s.split(“,”, 3);
for(String x : array) {
System.out.println(x);
}
The
”abc”
and
”def”
are split into the array and the remaining characters are put in a
String
in the third element of the array. The output of the code is
abc
def
g,hi,jklm,o
Search WWH ::
Custom Search