字符串标记器和管道符号

Thi*_*thi 4 java string stringtokenizer

    String s = "test -||- testing again -|- test_1 -||- testing again_1";
    StringTokenizer tokenizer = new StringTokenizer(s,"-|-");
    System.out.println(tokenizer.countTokens());

    while(tokenizer.hasMoreTokens()) {
        System.out.println(tokenizer.nextToken());
    }
Run Code Online (Sandbox Code Playgroud)

输出:

4
test 
 testing again 
 test_1 
 testing again_1
Run Code Online (Sandbox Code Playgroud)

算不应该是2 ..?

我尝试打印令牌,所有字符串都打印出来.不仅应将其视为一种标记.

我还从java API doc中读到了以下内容,

分隔符用于分隔令牌.令牌是不是分隔符的连续字符的最大序列

如果是这种情况,不应该使用我的分隔符" - | - "将字符串分成2个?

See*_*ose 6

A StringTokenizer使用一组分隔符字符,而不是您明显假设的分隔字符串.

因此,它会围绕它们发生任何分隔字符和标记.这会产生你得到的四个标记(省略空标记).

如果要通过分隔字符串拆分字符串,则必须使用String.split带有正则表达式的字符串:

String s = "test -||- testing again -|- test_1 -||- testing again_1";
String[] split = s.split("-\\|-"); // "|" is a special char in regex
System.out.println(split.length);
Run Code Online (Sandbox Code Playgroud)

输出为"2".