C++字符串递归子串
我试图递归地计算sub在str中出现的次数,而不需要子字符串重叠。我试图做的是str.findsub,如果它存在,则返回count+,调用函数,但不返回找到的位置:str.substrstr.findsub+sub.length 我尝试编写的代码:C++字符串递归子串,c++,recursion,C++,Recursion,我试图递归地计算sub在str中出现的次数,而不需要子字符串重叠。我试图做的是str.findsub,如果它存在,则返回count+,调用函数,但不返回找到的位置:str.substrstr.findsub+sub.length 我尝试编写的代码: int count = 0; int subCount(const std::string& str, const std::string& sub) { int len = str.length(); if(l
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 subCountcatcowcat,cat:预期为[2],但找到[3]
X次计数Cowcat,cow:预期为[1],但找到[3]
“+次计数猫头鹰、狗
X subCountcacatcowcat,cat:预期为[2],但发现[9]在请求帮助之前,您一定要使用调试器并检查基本错误 在该函数的开头将count初始化为零。 添加一条else语句,返回ifstr.findsub!的计数值字符串::npos。
我希望这能解决您的问题。非常感谢您。如果Scite有一个调试器,我会节省很多时间。
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);
}
}
}