Java Reference
In-Depth Information
22.6. StringTokenizer
The StringTokenizer class is an older and much simpler cousin of the Scan-
ner class, and its use is discouraged in new codethe Stringsplit method
(page 314 ) can be used as an alternative in many cases. A StringToken-
izer breaks a string into parts, using delimiter characters. A sequence
of tokens broken out of a string is, in effect, an ordered enumeration of
those tokens, so StringTokenizer implements the Enumeration interface [4]
(see page 617 ) . StringTokenizer provides methods that are more specific-
ally typed than Enumeration , which you can use if you know you are work-
ing on a StringTokenizer object. The StringTokenizer enumeration is ef-
fectively a snapshot because String objects are read-only. For example,
the following loop breaks a string into tokens separated by spaces or
commas:
[4] For historical reasons it implements Enumeration<Object> , not Enumeration<String> .
String str = "Gone, and forgotten";
StringTokenizer tokens = new StringTokenizer(str, " ,");
while (tokens.hasMoreTokens())
System.out.println(tokens.nextToken());
By including the comma in the list of delimiter characters in the
StringTokenizer constructor, the tokenizer consumes commas along with
spaces, leaving only the words of the string to be returned one at a time.
The output of this example is
Gone
and
forgotten
 
 
Search WWH ::




Custom Search