StringTokenizer countTokens() Method in Java with Examples
Last Updated :
28 Jan, 2019
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...