×

Java Programs

Java Practice

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



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.