Java Reference
In-Depth Information
Another version of the split() method requires a single argument of type String specifying the pattern.
This is equivalent to using the version with two arguments, where the second argument is zero, so you could
write the second statement in the previous code fragment as:
String[] words = text.split("[, .]"); // Delimiters are comma, space, or period
This produces exactly the same result as when you specify the second argument as 0. Now, it's time to
explore the behavior of the split() method in an example.
TRY IT OUT: Using a Tokenizer
Here you split a string completely into tokens with alternative explicit values for the second argument to
the split() method to show the effect:
public class StringTokenizing {
public static void main(String[] args) {
String text = "To be or not to be, that is the question."; //
String to segment
String delimiters = "[, .]";
// Delimiters are comma, space,
and period
int[] limits = {0, -1};
// Limit values to try
// Analyze the string
for(int limit : limits) {
System.out.println("\nAnalysis with limit = " + limit);
String[] tokens = text.split(delimiters, limit);
System.out.println("Number of tokens: " + tokens.length);
for(String token : tokens) {
System.out.println(token);
}
}
}
StringTokenizing.java
The program generates two blocks of output. The first block of output corresponding to a limit value of
0 is:
Analysis with limit = 0
Number of tokens: 11
To
be
or
not
to
be
Search WWH ::




Custom Search