StringTokenizer countTokens可以为零吗



我刚刚在一个方法中发现了一段Java代码:

if (param.contains("|")) {
  StringTokenizer st = new StringTokenizer(param.toLowerCase().replace(" ", ""), "|");
  if (st.countTokens() > 0) {
    ...
  }
} else {
  return myString.contains(param);
}

在上述情况下,countTokens是否可以小于1?

如果您试图标记化的字符串为空,则它可以,否则它将始终至少为1

示例1:

String myStr = "abcdefg";
StringTokenizer st = new StringTokenizer(myStr, ";");
int tokens = st.countTokens();
System.out.println("Number of tokens: " + tokens);
> "Number of tokens: 1"

示例2:

String myStr = "";
StringTokenizer st = new StringTokenizer(myStr, ";");
int tokens = st.countTokens();
System.out.println("Number of tokens: " + tokens);
> "Number of tokens: 0"

示例3:

String myStr = "abc;defg";
StringTokenizer st = new StringTokenizer(myStr, ";");
int tokens = st.countTokens();
System.out.println("Number of tokens: " + tokens);
> "Number of tokens: 2"

下面返回0:

  • new StringTokenizer("", "|").countTokens()
  • new StringTokenizer("|", "|").countTokens()
  • new StringTokenizer("||||", "|").countTokens()

所以countTokens()在时返回0

  • String为空
  • String只包含熟食计

看看这个

    String param="";
    StringTokenizer st = new StringTokenizer(param.toLowerCase().replace(" ", ""), "|");
    System.out.println(st.countTokens());

答案是0(零)

相关内容

  • 没有找到相关文章

最新更新