首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++字符串递归子程序

C++字符串递归子程序
EN

Stack Overflow用户
提问于 2014-12-02 23:09:08
回答 1查看 464关注 0票数 0

我试图递归地计算子在str中出现的次数,而不是子字符串重叠。我试图做的是str.find(sub),如果它存在count++,然后返回计数+回忆函数,但没有找到的位置:str.substr(str.find(sub) + sub.length())

代码语言:javascript
复制
Here are some examples:
subCcount("catcowcat", "cat") returns 2 
subCount("catcowcat", "cow") returns 1 
subCount("catcowcat", "dog") returns 0

我试着写的代码:

代码语言:javascript
复制
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(“猫猫”,“猫”):预期2,但发现3

X subCount(“猫猫”,“牛”):预期1,但发现3

+subCount(“猫猫”,“狗”)

X subCount(“仙人掌猫”,“猫”):预期2,但发现9

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-12-02 23:22:26

在寻求帮助之前,您绝对应该使用调试器并检查基本错误。

  • 在该函数的开头将计数初始化为零。
  • 添加一个返回if(str.find(sub) != string::npos)的count值的else语句。

我希望这能解决你的问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27260749

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档