StringTokenizer

1. Constructor

 

1. StringTokenizer(String str): Constructs a StringTokenizer object for parsing str. The default delimiters in java are "space", "tab ('\t')", "newline ('\n')", "carriage return ('\r')".
2. StringTokenizer(String str, String delim): Constructs a StringTokenizer object for parsing str and provides a specified delimiter.
3. StringTokenizer(String str, String delim, boolean returnDelims) : Construct a StringTokenizer object for parsing str, provide a specified delimiter, and specify whether to return the delimiter.

 

2. Introduction to the method

 

int countTokens() : Returns the number of times the nextToken method was called. If constructors 1 and 2 are used, the return is the number of separators.
boolean hasMoreElements(): Returns whether there are more separators.
boolean hasMoreTokens(): Same as above
String nextToken(): Returns the string from the current position to the next delimiter.
Object nextElement(): The result is the same as above, except that the life returns Object instead of String
String nextToken(String delim): Same as nextToken(), returns the result with the specified delimiter

 

example:

 

String s = new String("This is a test string");
StringTokenizer st = new StringTokenizer(s);
System.out.println( "Token Total: " + st.countTokens() );
while( st.hasMoreElements() ){
    System.out.println(st.nextToken());
}

 

Example 2:

 

String str = "100|66,55:200|567,90:102|43,54";

StringTokenizer strToke = new StringTokenizer(str, ":,|"); // Do not print delimiter by default
 // StringTokenizer strToke=new StringTokenizer(str,":,|",true); // Print delimiter
 // StringTokenizer strToke =new StringTokenizer(str,":,|",false); // Do not print the delimiter 
while (strToke.hasMoreTokens()){
    System.out.println(strToke.nextToken());
}

 

Note that StringTokenizer's delimiter does not need to use escape characters

3. Difference from split

 

String.Split() uses regular expressions, while StringTokenizer just uses word-by-word splitting of characters.
If you don't use regular expressions (StringTokenizer can't use regular expressions), StringTokenizer is the most efficient in intercepting strings.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325302237&siteId=291194637