img
Once you have created a StringTokenizer object, the nextToken( ) method is used to extract
consecutive tokens. The hasMoreTokens( ) method returns true while there are more tokens to
be extracted. Since StringTokenizer implements Enumeration, the hasMoreElements( ) and
nextElement( ) methods are also implemented, and they act the same as hasMoreTokens( ) and
nextToken( ), respectively. The StringTokenizer methods are shown in Table 18-1.
Here is an example that creates a StringTokenizer to parse "key=value" pairs. Consecutive
sets of "key=value" pairs are separated by a semicolon.
// Demonstrate StringTokenizer.
import java.util.StringTokenizer;
class STDemo {
static String in = "title=Java: The Complete Reference;" +
"author=Schildt;" +
"publisher=Osborne/McGraw-Hill;" +
"copyright=2007";
public static void main(String args[]) {
StringTokenizer st = new StringTokenizer(in, "=;");
while(st.hasMoreTokens()) {
String key = st.nextToken();
String val = st.nextToken();
System.out.println(key + "\t" + val);
}
}
}
The output from this program is shown here:
title  Java: The Complete Reference
author  Schildt
publisher  Osborne/McGraw-Hill
copyright  2007
Method
Description
int countTokens( )
Using the current set of delimiters, the method determines
the number of tokens left to be parsed and returns the
result.
boolean hasMoreElements( )
Returns true if one or more tokens remain in the string and
returns false if there are none.
boolean hasMoreTokens( )
Returns true if one or more tokens remain in the string and
returns false if there are none.
Object nextElement( )
Returns the next token as an Object.
String nextToken( )
Returns the next token as a String.
String nextToken(String delimiters)
Returns the next token as a String and sets the delimiters
string to that specified by delimiters.
TABLE 18-1
The Methods Defined by StringTokenizer
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home