Java Reference
In-Depth Information
A
StringTokenizer
object lets you break a string into tokens based on your definition of delimiters. It returns
one token at a time. You also have the ability to change the delimiter anytime. You can create a
StringTokenizer
by
specifying the string and accepting the default delimiters, which are a space, a tab, a new line, a carriage return, and a
line-feed character (
" \t\n\r\f"
) as follows:
// Create a string tokenizer
StringTokenizer st = new StringTokenizer("here is my string");
You can specify your own delimiters when you create a
StringTokenizer
as follows:
// Have a space, a comma and a semi-colon as delimiters
String delimiters = " ,;";
StringTokenizer st = new StringTokenizer("my text...", delimiters);
You can use the
hasMoreTokens()
method to check if you have more tokens and the
nextToken()
method to get
the next token from the string.
You can also use the
split()
method of the
String
class to split a string into tokens based on delimiters. The
split()
method accepts a regular expression as a delimiter. Listing 7-43 illustrates how to use the
StringTokenizer
and the
split()
method of the
String
class.
Listing 7-43.
Breaking a String into Tokens Using a StringTokenizer and the String.split() Method
// StringTokens.java
package com.jdojo.io;
import java.util.StringTokenizer;
public class StringTokens {
public static void main(String[] args) {
String str = "This is a test, which is simple";
String delimiters = " ,"; // a space and a comma
StringTokenizer st = new StringTokenizer(str, delimiters);
System.out.println("Tokens using a StringTokenizer:");
String token = null;
while(st.hasMoreTokens()) {
token = st.nextToken();
System.out.println(token);
}
// Split the same string using String.split() method
System.out.println("\nTokens using the String.split() method:");
String regex = "[ ,]+" ; /* a space or a comma */
String[] s = str.split(regex);
for(int i = 0 ; i < s.length; i++) {
System.out.println(s[i]);
}
}
}