【问题标题】:Wrong output from a while loop using indexOf [duplicate]使用 indexOf 的 while 循环的错误输出 [重复]
【发布时间】:2013-10-24 02:19:48
【问题描述】:

我试图找出一个字符串在另一个字符串中出现了多少次。对于我的测试,我对 wordOne 使用“ea”,对 wordTwo 使用“Ilikedthebestontheeastbeachleast”。我的输出为我的“外观”变量返回 2,它应该存储“ea”在 wordTwo 中出现的次数。它应该返回 3。

我尝试过弄乱变量初始化,并尝试以不同的方式思考数学,但我几乎没有想法。

以下是相关代码部分:

  int wordTwoLength = wordTwo.length();
  System.out.println(wordTwoLength);

  while (wordTwoLength > 0)
  {
     positionCount = wordTwo.indexOf(wordOne, positionCount);
     appearances++;
     wordTwoLength = (wordTwoLength - positionCount);
  }
  System.out.println(appearances);

谢谢!

编辑:我忘了补充说我尝试了其他测试输入并得到了疯狂的输出。对于某些人来说,它返回的数字会比预期的要高得多,而对于另一些人来说,它会返回的数字要低。

【问题讨论】:

标签: java string while-loop indexof


【解决方案1】:

所以现在的问题是 .indexOf 仍然返回 wordTwo 中“ea”的真实索引——它没有考虑你从哪里开始。此外,将 positionCount 设置为等于您找到单词的位置,然后再次从该位置搜索只会让您立即找到该单词的相同实例,而不是下一个。

wordTwo 中“ea”的第一个实例的索引是 18,因此 wordTwoLength 将设置为 32-18,即 14。然后您会在 wordTwo 中找到相同的 ea 实例,并且 wordTwoLength 将设置为14-18,或-4。然后退出 while 循环,出现次数为 2。

【讨论】:

  • 这是有道理的。我将尝试使用 wordOne 的长度来修改 positionCount 变量。这样,它将从 2 个位置开始,跳过它刚刚看到的单词。谢谢!
【解决方案2】:
for (int index = 0; (index = wordTwo.indexOf(wordOne, index)) > -1; index ++)
    appearances ++;

【讨论】:

    【解决方案3】:

    试试这个更简单的代码:

    class Demo{
    public static void main(String[] args){
        String wordOne = "ea";
        String wordTwo = "Ilikedthebestontheeastbeachleast";
        String[] arr = wordTwo.split(wordOne);
        int cnt = arr.length - 1;
        System.out.printf("[%s] has occured for %s time(s) in [%s]", wordOne, cnt, wordTwo);
    }
    

    }

    【讨论】:

    【解决方案4】:

    您可以通过“将字符串转换为字符数组”来简化上述工作。因为它会更高效(我认为)。我在这里提供了示例代码,

    String wordOne="Ilikedthebestontheeastbeachleast";
    String wordTwo="ea";
    int count=0;
    char[] arrayOne=wordOne.toCharArray();
    char [] arrayTwo=wordTwo.toCharArray();
    for(int i=0;i<=((arrayOne.length)-1);i++)
    {
    if(arrayTwo[0]==arrayOne[i]&&arrayTwo[1]==arrayOne[i+1])
    count+=1;
    }
    System.out.println("Pattern found "+count+" times.");
    

    这将满足您的需要,但使用 For 循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-27
      • 1970-01-01
      • 2012-01-02
      • 2016-05-15
      • 2019-02-17
      相关资源
      最近更新 更多