Use of StringTokenizer class in Java

StringTokenizer is a string-separated parsing type, which belongs to: java.util package.

The substring method in Java can decompose a string and return a substring of the original string.
If you want to decompose a string into individual words or tokens, StringTokenizer can help you.

StringTokenizer has two commonly used methods:

Note: All methods are public

1.hasMoreTokens()

The hasMoreElements()usage of this method is the same as that of the method , except that StringTokenizer implements the method to implement the Enumeration interface. From the declaration of StringTokenizer, you can see: class StringTokenizer implements Enumeration.

2.nextToken()

The nextElement()usage of this method is the same as that of the method, and returns the next token of this StringTokenizer.

Other methods

int countTokens(): Returns how many tokens are matched in total

		String s = new String("www.baidu.com");
        // 分词器构造函数三个参数,第一个是待分隔的字符串,第二个为分隔字符串,以字符为分隔单位(比如the,可能匹配到e,就会分隔),
        //第三个参数说明是否要把分割字符串作为标记返回
        StringTokenizer st = new StringTokenizer(s, ".", true);
        System.out.println("Token Total:" + st.countTokens());
        while (st.hasMoreElements()) {
    
    
            System.out.println(st.nextToken());
        }

result:
Insert picture description here

Three construction methods of StringTokenizer:

1.StringTokenizer(String str)

By default, "\t\n\r\f" (preceded by a space, quotation marks are not) is used as the separator.

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

Output:

Token:www
Token:baidu
Token:com

2.StringTokenizer(String str,String delim)

Construct a StringTokenizer object for parsing str and provide a specified separator.

3.StringTokenizer(String str,String delim,boolean returnDelims)

Construct a StringTokenizer object for parsing str and provide a specified separator. At the same time, specify whether to return the separator.

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

Output:

Token:www
Token:.
Token:baidu
Token:.
Token:com

Guess you like

Origin blog.csdn.net/qq_43229056/article/details/109672473