当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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


相关用法


注:本文由纯净天空筛选整理自Chinmoy Lenka大神的英文原创作品 StringTokenizer countTokens() Method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。