如何初始化递归函数的长度


int countChars(string str)
{
    int count = 0;
    if (str == "")
        return count;
    else
    {
        count++;// add a character to the count
        return count + countChars(str.substr(1));// function calls itself
    }
}

我需要使用上述函数并在下面的程序中调用,但我不确定如何正确初始化它。以下是我尝试过的,它不起作用。我不允许使用.length(),否则程序就会完成。

int main()
{
    char find = '';
    string str;
    int count = 0;
    int length = int(countChars);
    //ask the user for a sentence 
    cout << "Enter a sentence " << endl;
    getline(cin, str);
    //ask the user which letter they want the count of 
    cout << "Which letter would you like to find the number of appearances: " << endl;
    cin >> find;

    for (int i = 0; i < length; i++)
    {
        if (str[i] == find)
        {
            count++;
        }
    }
    cout << "the letter " << find << " appears " << length << " times " << endl;
    //waits for user to exit
    system("pause");
    cin.get();
}

似乎该函数应该计算字符串中字母的出现次数。如果是这样,则声明和定义不正确。它必须至少有两个参数,一个是 std::string 类型的对象,一个是 char 类型的对象。

这里显示了这样的递归函数的外观

#include <iostream>
#include <string>
size_t countChars( const std::string &s, char c )
{
    return s.empty() ? 0 : ( s[0] == c ) + countChars( { s, 1 }, c );
}
int main() 
{
    std::cout << "Enter a sentence ";
    std::string s;
    std::getline( std::cin, s );
    std::cout << "Which letter would you like to find the number of appearances: ";
    char c = '';
    std::cin >> c;

    std::cout << "The letter " << c 
              << " appears " << countChars( s, c ) 
              << " times " << std::endl;
    return 0;
}

程序输出可能如下所示

Enter a sentence My name is Alycia
Which letter would you like to find the number of appearances: a
The letter a appears 2 times 

如果你的意思是一个只计算字符串长度的函数,那么它看起来像

size_t countChars( const std::string &s )
{
    return s.empty() ? 0 : 1 + countChars( { s, 1 } );
}

并应在声明后调用

getline(cin, str);

最新更新