Thursday, 26 March 2015

StringTokenizer in Java

StringTokenizer in Java

The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to break string.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.

Constructors of StringTokenizer class

There are 3 constructors defined in the StringTokenizer class.
ConstructorDescription
StringTokenizer(String str)creates StringTokenizer with specified string.
StringTokenizer(String str, String delim)creates StringTokenizer with specified string and delimeter.
StringTokenizer(String str, String delim, boolean returnValue)creates StringTokenizer with specified string, delimeter and returnValue. If return value is true, delimiter characters are considered to be tokens. If it is false, delimiter characters serve to separate tokens.

Methods of StringTokenizer class

The 6 useful methods of StringTokenizer class are as follows:
Public methodDescription
boolean hasMoreTokens()checks if there is more tokens available.
String nextToken()returns the next token from the StringTokenizer object.
String nextToken(String delim)returns the next token based on the delimeter.
boolean hasMoreElements()same as hasMoreTokens() method.
Object nextElement()same as nextToken() but its return type is Object.
int countTokens()returns the total number of tokens.

Simple example of StringTokenizer class

Let's see the simple example of StringTokenizer class that tokenizes a string "my name is khan" on the basis of whitespace.
  1. import java.util.StringTokenizer;  
  2. public class Simple{  
  3.  public static void main(String args[]){  
  4.    StringTokenizer st = new StringTokenizer("my name is khan"," ");  
  5.      while (st.hasMoreTokens()) {  
  6.          System.out.println(st.nextToken());  
  7.      }  
  8.    }  
  9. }  
Output:my
       name
       is
       khan

Example of nextToken(String delim) method of StringTokenizer class

  1. import java.util.*;  
  2.   
  3. public class Test {  
  4.    public static void main(String[] args) {  
  5.        StringTokenizer st = new StringTokenizer("my,name,is,khan");  
  6.         
  7.       // printing next token  
  8.       System.out.println("Next token is : " + st.nextToken(","));  
  9.    }      
  10. }  
Output:Next token is : my

StringTokenizer class is deprecated now. It is recommended to use split() method of String class or regex (Regular Expression).

No comments:

Post a Comment