Java StringTokenizerBelongs to the java.util package, used to split strings.

StringTokenizer constructor methods:

  • 1. StringTokenizer(String str): Constructs a StringTokenizer object for parsing str. Java's default delimiters 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): Constructs a StringTokenizer object for parsing str, provides a specified delimiter, and specifies whether to return delimiters.

StringTokenizer common methods:

  • 1. int countTokens(): Returns the number of times the nextToken method has been called.
  • 2. boolean hasMoreTokens(): Returns whether there are more delimiters.
  • 3. boolean hasMoreElements(): Determines whether the enumeration (Enumeration) object still has data.
  • 4. String nextToken(): Returns the string from the current position to the next delimiter.
  • 5. Object nextElement(): Returns the next element of the enumeration (Enumeration) object.
  • 6. String nextToken(String delim): Similar to 4, returns the result using the specified delimiter.

Example 1

import java.util.*; public class Main { public static void main(String[] args) { String str = "example,google,taobao,facebook,zhihu"; //Use the comma (,) as the delimiter to split the string StringTokenizer st=new StringTokenizer(str,","); while(st.hasMoreTokens()) { System.out.println(st.nextToken()); } } }

The output is:

example
google
taobao
facebook
zhihu

Example 2

import java.util.*; public class Main { public static void main(String args[]) { System.out.println("Using the first constructor:"); StringTokenizer st1 = new StringTokenizer("Hello Example How are you", " "); while (st1.hasMoreTokens()) System.out.println(st1.nextToken()); System.out.println("Using the second constructor:"); StringTokenizer st2 = new StringTokenizer("JAVA : Code : String", " :"); while (st2.hasMoreTokens()) System.out.println(st2.nextToken()); System.out.println("Using the third constructor:"); StringTokenizer st3 = new StringTokenizer("JAVA : Code : String", " :", true); while (st3.hasMoreTokens()) System.out.println(st3.nextToken()); } }

The output is:

使用第一种构造函数:
Hello
Example
How
are
you
使用第二种构造函数:
JAVA
Code
String
使用第三种构造函数:
JAVA
 
:
 
Code
 
:
 
String