我们必须计算具有多个“this”子字符串的给定字符串中“this”的数量。例如。 “你好,这是新兵,这是老兵,这是” 会返回 4。
所以我正在使用:
StringTokenizer stringTokenizer1 = new StringTokenizer(input2);
ArrayList<String> arrayList1 = new ArrayList<String>();
int count=0;
int arrIndex = stringTokenizer1.countTokens();
for (int i = 0; i < stringTokenizer1.countTokens(); i++)
{
arrayList1.add(stringTokenizer1.nextToken());
}
for (String string2 : arrayList1)
{
if (string2.equals(string))
{
count++;
}
}
output1 = count;
System.out.println(output1);
只返回 2.
但是,如果 int arrindex
被赋值为 stringTokenizer1.countTokens() 并在循环条件下使用,它会给出正确的结果 4。为什么??
注意:使用JavaSE-1.6
最佳答案
条件 stringTokenizer1.countTokens()
会在您每次重新进入循环时计算。
Calculates the number of times that this tokenizer's nextToken method can be called before it generates an exception. The current position is not advanced.
这意味着 countTokens()
会在您每次调用 nextToken()
以你的例子:
- 对于 i=0,countTokens=4 -> 进入循环 -> 调用 nextToken() -> countTokens=3
- 对于 i=1,countTokens=3 -> 进入循环 -> 调用 nextToken() -> countTokens=2
- 对于 i=2,countTokens=2 -> 退出循环
关于java - StringTokenizer.countTokens() 在 for 循环条件中返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24445512/