c ++在字符串中查找重复的子字符串
Posted
技术标签:
【中文标题】c ++在字符串中查找重复的子字符串【英文标题】:c++ find repeated substring within string 【发布时间】: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
【参考方案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;
【讨论】:
以上是关于c ++在字符串中查找重复的子字符串的主要内容,如果未能解决你的问题,请参考以下文章
如何在javascript中使用 Map() 解决“由字符 A、C、G 和 T 组成的字符串。查找最长重复”的问题
怎么查找一个string 字符串中的子字符串出现的次数和位置