StringTokenizer is useful to break a String into small pieces called “tokens” and it is available in class of java.util package.

Procedure to use StringTokenizer class

  1. First receive String from keyboard,which contains different types of inputs.Assume that the input are separated by spaces.
    String str=br.readLine();
    
  2. Pass this String str to StringTokenizer object,So that it will be broken into pieces wherever a space is found.These tokens will be stored in StringTokenizer Object.

    StringTokenizer st=new StringTokenizer(str," ");
    
  3. Collect the individual tokens from st using nextToken() method of StringTokenizer class.
    String token=st.nextToken();
    
  4. These individual tokens represent the different types of inputs.these tokens can be converted into corresponding data types and can be used in the program.

Example:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

class Test {

	public static void main(String[] args) throws Exception {

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		System.out.println("enter any text");
		String inputs = br.readLine();
		
		System.out.println("Given String is:" + inputs);
		
		StringTokenizer st = new StringTokenizer(inputs, " ");
		
		String s1 = st.nextToken();
		String s2 = st.nextToken();
		String s3 = st.nextToken();
		
		System.out.println("s1=" + s1);
		System.out.println("s2=" + s2);
		System.out.println("s3=" + s3);
		br.close();
	}
}
/*
Output:
enter any text
Harold 34 78.90
Given String is:Harold 34 78.90
s1=Harold
s2=34
s3=78.90
*/

Note:
StringTokenizer st=new StringTokenizer(str,”,” true);
Returns delimiter as part of the output.

Important methods of StringTokenizer.

Method Description
countTokens() It returns no of tokens
hasMoreTokens() Test if there are more tokens available from the Tokenizer’s String
nextToken() Returns String
nextElement() Returns Object.
hasMoreElements()