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.
 
To read about Strings in Java pls click 
 

Constructor of StringTokenizer class

 
1. StringTokenizer(String object):
 
Constructs a string tokenizer for the specified string. It takes a default delimiter.
 
2. StringTokenizer(String object, String delimiters):
 
In this constructor, you can pass a delimiter according to need int form of string as a second argument.
 
3. StringTokenizer(String object, String delimiters, boolean deliasktoken):
 
This constructor has the same arguments except a boolean deliasktoken is an extra argument; this argument means if it's True then the delimiter character is also returned with the token.
 

Methods of the StringTokenizer class

 
1. int countTokens():

Calculates the number of times that this tokenizer's nextToken method can be called before it generates an exception.
 
2. boolean hasMoreTokens():
 
Tests if there are more tokens available from this tokenizer's string.
 
3. boolean hasMoreElements()
 
Returns the same value as the hasMoreTokens method.
 
4. String nextToken():
 
Returns the next token from this string tokenizer.
 
5. Object nextElement():
 
Returns the same value as the nextToken method, except that its declared return value is an Object rather than a String.
 
6. String nextToken(String delim):
 
Returns the next token in this string tokenizer's string.
 
Program
  1. import java .io.*;  
  2. import java.util.*;  
  3. class MyStringTokenizer  
  4. {  
  5.     public static void main(String arg[])throws IOException   
  6.     {  
  7.          String s="this ,is, the, example, of, StirgTokenizer";  
  8.          /* creating the object of stringTokenizer Class by passing the object string type s and second object passing as delimeter */  
  9.          StringTokenizer st=new StringTokenizer(s,",");  
  10.          /* hasMoreTokens() using for printing the return token it return the value true */  
  11.          while(st.hasMoreTokens())  
  12.         {  
  13.             System.out.println(st.nextToken());  
  14.         }  
  15.     }  
  16. }  
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.