C++字符串递归substr
问题描述:
我想递归地计算出子内出现str内没有子字符串重叠的次数。我所试图做的是str.find(sub)
,如果它存在count++
,然后返回计数+忆功能,但没有找到位置:str.substr(str.find(sub) + sub.length())
C++字符串递归substr
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( “catcowcat”, “猫”):预测[2],但发现[3]
X subCount(” catcowcat”, “牛”):预测[1]但发现[3]
“+ subCount( “catcowcat”, “狗”)
X subCount( “cacatcowcat”, “猫”):预期[2]但找到[9]
答
你应该明确地使用调试器,并在寻求帮助之前检查基本错误。
- 在该函数的开始处将计数初始化为零。
- 添加一个else语句,返回if(str.find(sub)!= string :: npos)的计数值。
我希望这可以解决您的问题。
非常感谢。如果Scite有调试器,我会节省很多时间。 – YoYo 2014-12-02 23:32:54