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.

Java String Programs »



Related Programs

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Top MCQs

Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.