使用StringTokenizer类的步骤如下:
import java.util.StringTokenizer;
StringTokenizer tokenizer = new StringTokenizer("Hello World");
while (tokenizer.hasMoreTokens()) {
// ...
}
String token = tokenizer.nextToken();
// ...
下面是一个完整的例子,将一个以逗号分隔的字符串分解成多个单词:
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
String input = "Hello,World,Java";
StringTokenizer tokenizer = new StringTokenizer(input, ",");
while (tokenizer.hasMoreTokens()) {
String word = tokenizer.nextToken();
System.out.println(word);
}
}
}
输出:
Hello
World
Java