简体   繁体   English

C ++字符串递归substr

[英]C++ String Recursion substr

I am trying to compute recursively the number of times that sub appears inside str, without the substrings overlapping. 我试图递归计算sub出现在str中的次数,而子字符串没有重叠。 What I am trying to do is str.find(sub) and if it exist count++ and then return the count + recalling the function but without the found position: str.substr(str.find(sub) + sub.length()) 我正在尝试做的是str.find(sub) ,如果它存在count++ ,然后返回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

The code I tried writing: 我尝试编写的代码:

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);
        }
    }
}

Testing the Code: 测试代码:

X subCount("catcowcat", "cat"): expected [2] but found [3] X subCount(“ catcowcat”,“ cat”):预期[2]但找到[3]

X subCount("catcowcat", "cow"): expected [1] but found [3] X subCount(“ catcowcat”,“ cow”):预期[1]但发现[3]

'+ subCount("catcowcat", "dog") '+ subCount(“ catcowcat”,“ dog”)

X subCount("cacatcowcat", "cat"): expected [2] but found [9] X subCount(“ cacatcowcat”,“ cat”):预期[2]但发现[9]

You should definitely use a debugger and check for basic errors before asking for help. 在寻求帮助之前,您绝对应该使用调试器并检查基本错误。

  • Initialize count to zero in the beginning of that function. 在该函数的开头将计数初始化为零。
  • Add an else statement returning count value for the if(str.find(sub) != string::npos). 添加else语句,返回if(str.find(sub)!= string :: npos)的计数值。

I hope this solves your problem. 我希望这能解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM