【问题标题】:c++ find repeated substring within stringc ++在字符串中查找重复的子字符串
【发布时间】:2013-11-20 05:42:39
【问题描述】:

我试图找出子字符串在字符串输入中重复的次数,但由于某种原因,当我调用该函数时,它给了我一个奇怪的数字。我已经在 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;
}

【问题讨论】:

  • 尝试将 counter 初始化为 0。如果你不这样做,它的开始是随机的。
  • uhuuuu 它有效....多么愚蠢的问题...谢谢@RetiredNinja

标签: c++ string function search


【解决方案1】:
//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;
}

【讨论】:

    猜你喜欢
    • 2014-05-09
    • 2020-02-24
    • 1970-01-01
    • 2014-02-27
    • 2016-10-05
    • 1970-01-01
    • 2013-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多