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