使用递归计算c中单词(字符串)中字母出现的次数

标签 c string recursion

这是我在 com sci 实验室的期末考试,我想知道主函数是否正确,我刚刚添加了另一个函数,因为我不知道如何在字符串中使用递归来计算这个字符出现的次数。,im真的很难受。请帮我。 :)

#include<stdio.h>
#include<string.h>

int count_chars(const char* string, char ch);


int main()
{
    char string[BUFSIZ];
    char ch[2];
    int count;

    printf ("Please enter a line of text, max %d characters\n", sizeof(string));

    if (fgets(string, sizeof(string), stdin) != NULL)
        printf ("You entered: %s\n", string);

    printf("Input the letter you want to be counted: ");
    gets(ch);

    count=count_chars(const char* string, char ch);
    printf("The number of times the letter occurs in the word above is: %d", count);

    return 0;
}


int count_chars(const char* string, char ch)
{
    int count = 0;

    for(; *string; count += (*string++ == ch)) ;
    return count;
}

例如;输入是:“aabbabc”那么您需要查找的字符是 b,所以程序应该像这样运行:(这是作为提示给我的)但他说你应该将其转换为(函数?)我尝试了但不起作用。

"b"  "aabbabc"
if 'b'==st[0]
1+cnt('b', "abbabc");
else 
cnt('b' , "abbabc");

最佳答案

这会起作用:

int count_chars(const char* string, char ch) {
  return *string? count_chars(string + 1, ch) + (ch == *string) : 0;
}

关于使用递归计算c中单词(字符串)中字母出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19309969/

相关文章:

c# - 如何在 WebMatrix razor C# 中实现正则表达式(或类似表达式)?

language-agnostic - 递归如何使运行时内存的使用变得不可预测?

c - 使用 getchar 输入字符串

c - 如果a是数组(比如int a[4];),那么&a是什么?

c++如何在 vector 中的特定位置显示元素的字符串属性?

java - 字符串翻转不起作用,不明白为什么?导致越界异常

c - 在 C 中格式化文本

c++ - 至强的 gcc 优化标志?

java - 选择排序递归调用

javascript - js在递归函数中不起作用