Next: None. Up: Text files. Previous: The BufferedReader class.


The StringTokenizer class

The final class we're going to look at isn't part of the java.io package at all - it's part of the java.util package. It's basic purpose is to break a string into tokens - basically, breaking it into words.

Breaking a string into tokens is often often handy when you're reading from a file: You often don't particularly care about the space separating the tokens, you just want to get the data within the tokens.

StringTokenizer(String data)
Creates a StringTokenizer, which can be used to fetch the tokens contained within data. Tokens are considered to be split by any combination of white-space characters (the space character, the tab character, the newline character, or the carriage return character).

StringTokenizer(String data, String delims)
Creates a StringTokenizer, which can be used to fetch the tokens contained within data. Tokens are considered to be split by any combination of characters contained in the string delims.

After creating a StringTokenizer object, you can use the following instance methods to get information about the tokens.

boolean hasMoreTokens()
Returns true if there are any tokens left in the token sequence.

String nextToken()
Deletes and returns the next token in the token sequence.

int countTokens()
Returns the number of tokens left in the token sequence.

As an example, the following program would read a line from the user and print out all the words the user typed.

import java.util.*;
import csbsju.cs160.*;

public class PrintWords {
    public static void main(String[] args) {
        IO.print("Line: ");
        String line = IO.readLine();
        StringTokenizer tokens = new StringTokenizer(line);
        while(tokens.hasMoreTokens()) {
            IO.println(tokens.nextToken());
        }
    }
}

Exercise


Next: None. Up: Text files. Previous: The StringTokenizer class.