[英]how to initialize the recursive function for length
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
}
}
I need to take the above function and call in in the program below and I'm not sure how to initialize it properly.我需要使用上面的函数并在下面的程序中调用,但我不确定如何正确初始化它。 Below is what I tried and it doesn't work.以下是我尝试过的,但不起作用。 I'm not allowed to use the .length()
because otherwise the program would be done.我不允许使用.length()
因为否则程序将完成。
int main()
{
char find = '\0';
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();
}
It seems the function should count the number of appearances of a letter in a string.该函数似乎应该计算字符串中字母出现的次数。 If so then it is declared and defined incorrectly.如果是,那么它的声明和定义不正确。 It has to have at least two parameters an object of type std::string
and an object of type char
.它必须至少有两个参数,一个是std::string
类型的对象,另一个是char
类型的对象。
Here is shown how such a recursive function can look这里展示了这种递归函数的外观
#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 = '\0';
std::cin >> c;
std::cout << "The letter " << c
<< " appears " << countChars( s, c )
<< " times " << std::endl;
return 0;
}
The program output might look like程序输出可能看起来像
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
If you mean a function that just calculates the length of a string then it can look like如果你的意思是一个只计算字符串长度的函数,那么它看起来像
size_t countChars( const std::string &s )
{
return s.empty() ? 0 : 1 + countChars( { s, 1 } );
}
and shall be called after the statement并应在声明后调用
getline(cin, str);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.