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:
import java.util.*;
public class StringTokenizer_Demo1 {
public static void main(String args[])
{
StringTokenizer str_arr
= new StringTokenizer(
"Lets practice at GeeksforGeeks" );
int count = str_arr.countTokens();
System.out.println( "Total number of Tokens: "
+ count);
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:
import java.util.*;
public class StringTokenizer_Demo2 {
public static void main(String args[])
{
StringTokenizer str_arr
= new StringTokenizer(
"Welcome to GeeksforGeeks" );
int count = str_arr.countTokens();
System.out.println( "Total number of Tokens: "
+ count);
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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!