Q:

Java program to separate all tokens (words) using StringTokenizer

0

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.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now