StringTokenizer Count Tokens

This is an example of how to use a StringTokenizer to count the tokens of a String. The StringTokenizer is used to break a String into tokens. Using a StringTokenizer to count the tokens of a String implies that you should:

  • Get a new StringTokenizer for a specified String, using the StringTokenizer(String str) constructor.
  • Invoke countTokens() API method of StringTokenizer. The method calculates the number of times that this tokenizer’s nextToken() method can be called before it generates an exception, that is the number of tokens that the String of the tokenizer has.
  • While hasMoreTokens() API method of StringTokenizer returns true, invoke nextToken() method of StringTokenizer to get the tokens of this String and invoke countTokens() method again. Each time a new token is returned, the countTokens() method returns one less than before.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.util.StringTokenizer;

public class StringTokenizerCountTokens {
	public static void main(String[] args) {
		StringTokenizer tokenizer = new StringTokenizer("Java Code Geeks - Java Examples");
		System.out.println("Remaining Tokens: " + tokenizer.countTokens());
		// loop through tokens
		while (tokenizer.hasMoreTokens()) {
			System.out.println("Token:" + tokenizer.nextToken());
			System.out.println("Remaining Tokens: " + tokenizer.countTokens());



Remaining Tokens: 6
Remaining Tokens: 5
Remaining Tokens: 4
Remaining Tokens: 3
Remaining Tokens: 2
Remaining Tokens: 1
Remaining Tokens: 0

This was an example of how to use a StringTokenizer to count the tokens of a String in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button