0
我想递归地计算出子内出现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]
非常感谢。如果Scite有调试器,我会节省很多时间。 – YoYo 2014-12-02 23:32:54