📜  Java中的StringTokenizer

📅  最后修改于: 2020-09-23 09:04:34             🧑  作者: Mango

Java中的StringTokenizer

java.util.StringTokenizer类允许您将字符串分成令牌。这是打破字符串的简单方法。

它没有提供区分数字,带引号的字符串,标识符等的功能,例如StreamTokenizer类。我们将在I/O一章中讨论StreamTokenizer类。

StringTokenizer类的构造方法

StringTokenizer类中定义了3个构造函数。

Constructor Description
StringTokenizer(String str) creates StringTokenizer with specified string.
StringTokenizer(String str, String delim) creates StringTokenizer with specified string and delimeter.
StringTokenizer(String str, String delim, boolean returnValue) creates StringTokenizer with specified string, delimeter and returnValue. If return value is true, delimiter characters are considered to be tokens. If it is false, delimiter characters serve to separate tokens.

StringTokenizer类的方法

StringTokenizer类的6个有用方法如下:

Public method Description
boolean hasMoreTokens() checks if there is more tokens available.
String nextToken() returns the next token from the StringTokenizer object.
String nextToken(String delim) returns the next token based on the delimeter.
boolean hasMoreElements() same as hasMoreTokens() method.
Object nextElement() same as nextToken() but its return type is Object.
int countTokens() returns the total number of tokens.

StringTokenizer类的简单示例

让我们看一下StringTokenizer类的简单示例,该类在空格的基础上标记字符串“我的名字是可汗”。

import java.util.StringTokenizer;  
public class Simple{  
 public static void main(String args[]){  
   StringTokenizer st = new StringTokenizer("my name is khan"," ");  
     while (st.hasMoreTokens()) {  
         System.out.println(st.nextToken());  
     }  
   }  
}  

StringTokenizer类的nextToken(String delim)方法的示例

import java.util.*;  
  public class Test {  
   public static void main(String[] args) {  
       StringTokenizer st = new StringTokenizer("my,name,is,khan");  
              // printing next token  
      System.out.println("Next token is : " + st.nextToken(","));  
   }      
}  

现在不建议使用StringTokenizer类。建议使用String类或regex(正则表达式)的split()方法。