使用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