Java StringTokenzier

Java中substring方法可以分解字符串,返回的是原字符串的一个子字符串。如果要讲一个字符串分解为一个一个的单词或者标记,StringTokenizer可以帮你。

1     public static void main(String[] args) {  
2      StringTokenizer st = new StringTokenizer("www.baidu.com", ".b");  
3      while(st.hasMoreElements()){  
4      System.out.println("Token:" + st.nextToken());  
5      }  
6      }  

输出:
Token:www
Token:baidu
Token:com

StringTokenizer有两个常用的方法:

1.hasMoreTokens()。这个方法和hasMoreElements()方法的用法是一样的,只是StringTokenizer为了实现Enumeration接口而实现的方法,从StringTokenizer的声明可以看到:class StringTokenizer implements Enumeration<Object>。

2.nextToken()。这个方法和nextElement()方法的用法是一样的,返回此 StringTokenizer 的下一个标记。

StringTokenizer的三个构造方法:

1.StringTokenizer(String str)。默认以” f”(前有一个空格,引号不是)为分割符。
源码:

/**
* Constructs a string tokenizer for the specified string. The
* tokenizer uses the default delimiter set, which is
* <code>"&nbsp;&#92;t&#92;n&#92;r&#92;f"</code>: the space character,
* the tab character, the newline character, the carriage-return character,
* and the form-feed character. Delimiter characters themselves will
* not be treated as tokens.
*
* @param str a string to be parsed.
* @exception NullPointerException if str is <CODE>null</CODE>
*/
public StringTokenizer(String str) {
this(str, " f", false);

  public static void main(String[] args) {  
 
     StringTokenizer st = new StringTokenizer("www baidu com");  
     while(st.hasMoreElements()){  
     System.out.println("Token:" + st.nextToken());  
     }  
     } 
 

  输出:Token:www

                  Token:baidu

                  Token:com

public static void main(String[] args) {  
 
  StringTokenizer st = new StringTokenizer("www.baidu.com", ".", true);  
 
  while(st.hasMoreElements()){  
 
  System.out.println("Token:" + st.nextToken());  
 
  }  
 
  }

输出:Token:wwwToken:.Token:baiduToken:.Token:com

原文地址:https://www.cnblogs.com/Firesun/p/9430372.html