我试图递归地计算子在str中出现的次数,而不是子字符串重叠。我试图做的是str.find(sub),如果它存在count++,然后返回计数+回忆函数,但没有找到的位置:str.substr(str.find(sub) + sub.length())
Here are some examples:
subCcount("catcowcat", "cat") returns 2
subCount("catcowcat", "cow") returns 1
subCount("catcowcat", "dog") returns 0我试着写的代码:
int count = 0;
int subCount(const std::string& str, const std::string& sub)
{
int len = str.length();
if(len == 0)
{
return 0;
}
else
{
if(str.find(sub) != string::npos)
{
count++;
return count + subCount(str.substr(str.find(sub) + sub.length()), sub);
}
}
}测试守则:
X subCount(“猫猫”,“猫”):预期2,但发现3
X subCount(“猫猫”,“牛”):预期1,但发现3
+subCount(“猫猫”,“狗”)
X subCount(“仙人掌猫”,“猫”):预期2,但发现9
发布于 2014-12-02 23:22:26
在寻求帮助之前,您绝对应该使用调试器并检查基本错误。
我希望这能解决你的问题。
https://stackoverflow.com/questions/27260749
复制相似问题