Write a program to separate all tokens (words) using StringTokenizer


This Java program prompts the user to enter a string and then counts the number of tokens (words) in the string using the StringTokenizer class. The program starts by reading a string from the user using the Scanner class, and then creates a StringTokenizer object with the string and a space delimiter.

The program then enters a loop that continues as long as there are more tokens in the string. In each iteration of the loop, the program prints the number of remaining tokens using the countTokens() method, and then prints the next token using the nextToken() method.

Source Code

import java.util.Scanner;
import java.util.StringTokenizer;
public class Count_Tokens 
{
	public static void main(String[] args) 
	{
		String str;
		Scanner input = new Scanner (System.in);
		System.out.print("Enter the String : ");
 
		str = input.nextLine();
		StringTokenizer st = new StringTokenizer(str, " ");
 
		// search for token while the string ends.
		while(st.hasMoreTokens())
		{
			System.out.println("Remaining are : " + st.countTokens());
			System.out.println(st.nextToken());
		}
	}
}

Output

Enter the String : java
Remaining are : 1
java

Example Programs