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

标签 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;
}

最佳答案

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

关于C++在字符串中查找重复的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20088263/

相关文章:

c++ - 如果存储字符串的 char 数组小于字符串,那么 C++ 真正存储字符串的位置是什么?

python 密码检查器 : numbers and symbols

javascript - 函数返回 'undefined'

按键时 JavaScript 移动

python - 一个函数可以有多个名称吗?

c++ - 如何使用相对路径将共享库与 CMake 链接

c++ - 读取文件并将其添加到文本框 : string conversion issue

c - 遍历 C 中的 char 数组

c++ - 如何创建 128 位整数文字?

c++ - c++ operator |= atomic 是多核处理器吗?