c ++在字符串中查找重复的子字符串

时间:2013-11-20 05:42:40

标签: c++ string function search

我试图找到子串在字符串输入中重复的次数但由于某种原因,当我调用该函数时,它给了我一个奇怪的数字。我已经在main中测试了这个函数并且它工作正常但是当我创建一个独立的函数时它不起作用。

提前谢谢

#include <iostream>
#include <cstring>
#include <string>

using namespace std;

int checkHope(string word1)
    {
    int answer;
    int counter;
    for(int i = 0; word1[i] != '\0'; i++)
    {
        answer = word1.find("h", i);
        if ((word1.find("o", (answer+1)) == i+1) && (word1.find("e", (answer+3)) == i+3)) counter++;
    }
    return counter;
    }

int main()
{
    string word1;

    cout << "Please enter a word to check how many times the word \"hope\" appears. You can also have any letter instead of p.: ";
    getline(cin, word1);
    cout << checkHope(word1);

    return 0;
}

1 个答案:

答案 0 :(得分:0)

//This will work, 
//Changes initialize counter to 0, add condition to check alphabet 'p' also in if condition


#include <iostream>
#include <cstring>
#include <string>

using namespace std;

int checkHope(string word1)
{
  int answer;
  int counter=0;
  for(int i = 0; word1[i] != '\0'; i++)
  {
    answer = word1.find("h", i);
    if ((word1.find("o", (answer+1)) == i+1)
          &&  (word1.find("p", (answer+2)) == i+2)
          && (word1.find("e", (answer+3)) == i+3))
           counter++;
  }
  return counter;
}

int main()
{
  string word1;

  cout << "Please enter a word to check how many times the word \"hope\" appears. You can also have any letter instead of p.: ";
  getline(cin, word1);
  cout << checkHope(word1);

  return 0;
}