Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

StringTokenizer countTokens() Method in Java with Examples

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

The countTokens() method of StringTokenizer class calculate the number of times that this tokenizer’s nextToken method can be called before the method generates any further exception.
Note: The current position is not advanced during the process.

Syntax:

public int countTokens()

Parameters: The method does not take any parameters.

Return Value: The method is used to return the number of tokens remaining in the string using the current delimiter set.

Below programs illustrate the working of countTokens() Method of StringTokenizer:
Example 1:




// Java code to illustrate countTokens() method
  
import java.util.*;
  
public class StringTokenizer_Demo1 {
    public static void main(String args[])
    {
  
        // Creating a StringTokenizer
        StringTokenizer str_arr
            = new StringTokenizer(
                "Lets practice at GeeksforGeeks");
  
        // Counting the tokens
        int count = str_arr.countTokens();
        System.out.println("Total number of Tokens: "
                           + count);
  
        // Print the tokens
        for (int i = 0; i < count; i++)
            System.out.println("token at [" + i + "] : "
                               + str_arr.nextToken());
    }
}


Output:

Total number of Tokens: 4
token at [0] : Lets
token at [1] : practice
token at [2] : at
token at [3] : GeeksforGeeks

Example 2:




// Java code to illustrate countTokens() method
  
import java.util.*;
  
public class StringTokenizer_Demo2 {
    public static void main(String args[])
    {
  
        // Creating a StringTokenizer
        StringTokenizer str_arr
            = new StringTokenizer(
                "Welcome to GeeksforGeeks");
  
        // Counting the tokens
        int count = str_arr.countTokens();
        System.out.println("Total number of Tokens: "
                           + count);
  
        // Print the tokens
        for (int i = 0; i < count; i++)
            System.out.println("token at [" + i + "] : "
                               + str_arr.nextToken());
    }
}


Output:

Total number of Tokens: 3
token at [0] : Welcome
token at [1] : to
token at [2] : GeeksforGeeks

My Personal Notes arrow_drop_up
Last Updated : 28 Jan, 2019
Like Article
Save Article
Similar Reads
Related Tutorials