Java中的 StringTokenizer countTokens() 方法及示例
StringTokenizer 类的countTokens()方法计算在该方法生成任何进一步的异常之前可以调用此标记器的nextToken方法的次数。
注意:当前位置在此过程中不前进。
句法:
public int countTokens()
参数:该方法不带任何参数。
返回值:该方法用于返回使用当前分隔符集的字符串中剩余的标记数。
下面的程序说明了 StringTokenizer 的 countTokens() 方法的工作:
示例 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());
}
}
输出:
Total number of Tokens: 4
token at [0] : Lets
token at [1] : practice
token at [2] : at
token at [3] : GeeksforGeeks
示例 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());
}
}
输出:
Total number of Tokens: 3
token at [0] : Welcome
token at [1] : to
token at [2] : GeeksforGeeks