【发布时间】:2014-12-02 23:09:08
【问题描述】:
我正在尝试递归计算 sub 在 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("catcowcat", "cat"): 预期 [2] 但找到 [3]
X subCount("catcowcat", "cow"): 预期 [1] 但找到 [3]
'+ subCount("catcowcat", "dog")
X subCount("cacatcowcat", "cat"): 预期 [2] 但找到 [9]
【问题讨论】: