How to Use the StringTokenizer Class in JAVA


StringTokenizer class

The StringTokenizer class allows us to break a string into tokens. The StringTokenizer method does not distinguish among the identifiers quoted string, numbers, skip comment; and the StringTokenizer class implements the Enumeration interfaceTo use a StringTokenizer that you specify in an input String which contains delimiters.

Delimiters are nothing but only characters that separate tokens for example comma (,) colon(:) semicolon(;). The default delimiters are the whitespace characters space, tab, newline and carriage return.

The constructor of StringTokenizer class

StringTokenizer(String object):

Constructs a string tokenizer for the specified string. It takes a default delimiter.

StringTokenizer(String object,String delimiters):

In this constructor you can pass a delimiter according to need int form of string as a second arument.

StringTokenizer(String object,String delimiters,boolean deliasktoken):

This constructor has the same agruments except a boolean deliasktoken is an extra argument; this arument means if its True then the delimeiter charcter is also returned with the token.

Methods of of the StringTokenizer class

int countTokens():
Calculates the number of times that this tokenizer's nextToken method can be called before it generates an exception.

boolean hasMoreTokens():

Tests if there are more tokens available from this tokenizer's string.

boolean hasMoreElements()

Returns the same value as the hasMoreTokens method.

String nextToken():

Returns the next token from this string tokenizer.

Object nextElement():

Returns the same value as the nextToken method, except that its declared return value is an Object rather than a String.

String nextToken(String delim):

Returns the next token in this string tokenizer's string.

Program

import java .io.*;
import java.util.*;
class MyStringTokenizer
{
    public static void main(String arg[])throws IOException
    {
         String s="this ,is, the, example, of, StirgTokenizer";
         /* creating the object of stringTokenizer Class by passing the object string type s and second object passing as delimeter */
         StringTokenizer st=new StringTokenizer(s,",");
         /* hasMoreTokens() using for printing the return token it return the value true */
         while(st.hasMoreTokens())
        {
            System.out.println(st.nextToken());
        }
    }
}

Output

strintokenizer.gif

Summary

The StringTokenizer class helps to break a string object into tokens as determined by the delimiter passed into the parameter, which works as a separator you can make your own delimiter and if you do not specify a delimiter then it uses default delimiters.

Up Next
    Ebook Download
    View all
    Learn
    View all