【问题标题】:C++ String Recursion substrC++ 字符串递归子串
【发布时间】: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]

【问题讨论】:

    标签: c++ recursion


    【解决方案1】:

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

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

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

    【讨论】:

    • 非常感谢。如果 Scite 有调试器,我会节省很多时间。
    猜你喜欢
    • 2017-10-28
    • 2020-06-07
    • 2011-09-27
    • 2015-05-13
    • 1970-01-01
    • 2014-02-19
    • 2016-07-04
    • 2016-11-26
    • 2021-07-27
    相关资源
    最近更新 更多