Home » Java programs » Java String programs

Java program to separate all tokens (words) using StringTokenizer

In this java program, we are going to learn how to access all tokens (words) from a string using StringTokenizer() class?
Submitted by IncludeHelp, on November 01, 2017

Given a string and we have to access, print all words (tokens) separating them by space in java.

Example:

Input string: We are $ {} 7 ? here.
Output
We 
are
$
{}
7
?
here.

In this program, we are taking a string from the user and accessing all words (tokens) by separating them using space (here, space is a delimiter) and then printing them on the output screen.

Program

import java.util.Scanner;
import java.util.StringTokenizer;

public class CountTokens 
{
	public static void main(String[] args) 
	{
		//create StringTokenizer object
		String S;
		Scanner scan = new Scanner (System.in);

		// enter your string here.
		System.out.print("Enter the string : ");

		// will read string and store it in "S" for further process.
		S = scan.nextLine();
		StringTokenizer st = new StringTokenizer(S, " ");

		// search for token while the string ends.
		while(st.hasMoreTokens())
		{
			// print all the tokens.
			System.out.println("Remaining are : " + st.countTokens());
			System.out.println(st.nextToken());
		}
	}
}

Output

Enter the string : We are $ {} 7 ? here.
Remaining are : 7
We
Remaining are : 6
are
Remaining are : 5
$
Remaining are : 4
{}
Remaining are : 3
7
Remaining are : 2
?
Remaining are : 1
here.





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.