无法让我的递归函数正确计算字符串中的字母(c ++)

Can't get my recursive function to count letters in a string correctly (c++)

本文关键字:字符串 我的 递归函数 计算      更新时间:2023-10-16

我有一个家庭作业,要求我使用递归函数来计算用户给定字符串中的 a 数量。我不想得到答案,但如果有人能给我一点指导,那就太好了。它正确地调用了自己,但我无法弄清楚如何正确计算 a 的数量。这是我的代码。

int charCounter(string str, int counter)
{
    if (str == "")
    {
        return counter;
    }
    else if (str.substr(1) == "a");
    {
        counter++;
        return counter + charCounter(str.substr(1),counter);
    }
}

首先,您需要知道字符串是字符数组。 例如 "hey" => ['h', 'e', 'u']。

当你处理递归函数时,你需要的第一件事是你的停止条件,你声明为 str == " 或当 str 为空时。

每次调用递归函数

时,您都想检查字符串是否为空,然后返回计数器,否则递增计数器,从字符串中删除一个字符,然后递归调用传递新str和当前计数器的函数。

确保在调用递归函数集计数器 = 0

伪代码

recursiveStrCounter(str, counter) {
    if empty str {
       return counter
    }
    counter++
    remove one char from str
    return recursiveStrCounter(str, counter)
}
print recursiveStrCounter(str, 0)

希望它有帮助。

稍微改变函数会有所帮助

int countstring(string s) {
        int counter = 0;
        if (s.length() == 0)
            return counter;
        else {
            if (s[0]== 'a')
                counter++;
            string newstring = s.substr(1);
            return counter + countstring(newstring);
        }
    }