-2

我试图找出一个字符串出现在另一个字符串中的次数。对于我的测试,我对 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);

谢谢!

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

4

4 回答 4

0

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

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

于 2013-10-16T04:55:58.990 回答
0
for (int index = 0; (index = wordTwo.indexOf(wordOne, index)) > -1; index ++)
    appearances ++;
于 2013-10-16T04:57:26.630 回答
0

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

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 循环。

于 2013-10-16T06:33:20.893 回答
0

试试这个更简单的代码:

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);
}

}

于 2013-10-16T07:32:21.603 回答