THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

The StringTokenizer class has several methods to control what is considered a word, whether it should
understand numbers or strings specially, and so on:


publicStringTokenizer(String str, String delim,boolean
returnTokens)

Constructs a StringTokenizer on the string str, using the characters in
delim as the delimiter set. The returnTokens boolean determines
whether delimiters are returned as tokens or skipped. If they are returned as
tokens, each delimiter character is returned separately.

publicStringTokenizer(String str, String delim)

Equivalent to StringTokenizer(str, delim, false), meaning
that delimiters are skipped, not returned.

publicStringTokenizer(String str)

Equivalent to StringTokenizer(str," \t\n\r\f"), meaning that
the delimiters are the whitespace characters and are skipped.

public booleanhasMoreTokens()

Returns true if more tokens exist.

public StringnextToken()

Returns the next token of the string. If there are no more tokens, a
NoSuchElementException is thrown.

public StringnextToken(String delim)

Switches the delimiter set to the characters in delim and returns the next
token. There is no way to set a new delimiter set without getting the next
token. If there are no more tokens, a NoSuchElementException is
thrown.

public intcountTokens()

Returns the number of tokens remaining in the string using the current
delimiter set. This is the number of times nextToken can return before it
will generate an exception. When you need the number of tokens, this
method is faster than repeatedly invoking nextToken because the token
strings are merely counted, not constructed and returned.

The methods StringTokenizer implements for the Enumeration interface (hasMoreElements and
nextElement) are equivalent to hasMoreTokens and nextToken, respectively.


The delimiter characters are processed individually when StringTokenizer looks for the next token, so it
cannot identify tokens separated by a multicharacter delimiter. If you need a multicharacter delimiter, use
either the String class's split method or a Scanner.


Exercise 22.14: Write a method that will take a string containing floating-point numbers, break it up using
whitespace as the delimiter, and return the sum of the numbers.

Free download pdf