如何初始化递归函数的长度
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
}
}
我需要使用上述函数并在下面的程序中调用,但我不确定如何正确初始化它。以下是我尝试过的,它不起作用。我不允许使用.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);
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何在Elixir中调用递归函数并行
- 递归函数有效,但无法记忆
- 为什么我的递归函数按降序打印,然后按升序打印?
- 为什么递归函数的最终输出是 5?
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- 有没有办法使用递归函数找到数组中最小值的 INDEX?C++
- 尝试使用 OpenMP 并行化递归函数的冗余计算
- 无递归的初始化
- 如何初始化递归函数的长度
- 使用条件运算符递归计算模板化值或函数时出现错误 C1202(堆栈溢出)
- 如果结构作为递归函数中的参数传递,如何初始化结构的成员变量
- 递归调用模板化函数 (C++)
- 在C++中使用OpenMP实现递归函数的并行化
- 模板化递归函数的语法是什么
- 用新的模板参数递归调用模板化函数
- 类在递归函数内部实例化,c++
- c++ /Java递归变量初始化
- 在递归函数中通过引用传递的数组 - 最后一列重新初始化
- 更改类型后递归为模板化函数