无法让我的递归函数正确计算字符串中的字母(c ++)
Can't get my recursive function to count letters in a string correctly (c++)
我有一个家庭作业,要求我使用递归函数来计算用户给定字符串中的 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);
}
}
相关文章:
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 我应该如何修改此代码以使用给定字符串中的字母打印菱形图案
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 我的逻辑反转字符串中的元音有什么问题?
- 为什么我的字符串变量没有打印完整的字符串?
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 为什么我的子类不继承父类的字符串?
- 为什么我的 cout 在输出中没有显示字符串?
- 为什么在为其分配编号后无法显示我的字符串值?
- 如何正确解析子字符串,以便它们对我的新手计算器有效?
- 我的 c++ 程序似乎没有发现字符串和我拥有但输入使用 getline 的变量之间的比较
- 为什么我的驱动程序只读取部分字符串?
- 我的求解(字符串 a、字符串 b)的输出与随机哈希中的预期输出不匹配
- 为什么我得到长度仅为 3 的字符串排列的输出?
- 为什么我的结构在包含字符串时崩溃?
- 如何将我的每个矢量字符串转换为纪元时间日期
- 用字符串初始化我的类的对象
- 我的字符串数组一次打印出前两个字符串
- 当我的 if 语句在字符串中找到空格时,在无限循环中切换
- 解析字符串:我的代码在测试后显然可以工作,但不雅