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

使用递归计算字母在c中的单词(字符串)中出现的次数,c,string,recursion,C,String,Recursion,这是我在com sci实验室的期末考试,我想知道主函数是否正确,我刚刚添加了另一个函数,因为idk如何在字符串中使用递归来计算这个字符出现的次数。我真的很难处理这个问题。请帮帮我。:) 这将有助于: int count_chars(const char* string, char ch) { return *string? count_chars(string + 1, ch) + (ch == *string) : 0; } 递归函数应该像所有递归函数一样工作。你需要: 基本情况(停止递

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

这将有助于:

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

递归函数应该像所有递归函数一样工作。你需要:

  • 基本情况(停止递归)
  • 减少的输入集(从原始输入集缩减,以便实际达到基本输入集)
  • 您的函数将如下所示(在伪代码中)


    #include#include+1,
    +ch
    将为您提供一些非常有趣的总结。它实际上相当优雅,你只需盯着它看一分钟。我明白了,并相应地向上勾选。我知道你们在做什么,但这在帕伦资格认证中更容易理解。我完全同意你们的观点,谢谢你们的支持。当然,最后一个版本更好。
    "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;
    }
    
    function count_chars(string s, char ch){
       int count = 0 
    
       if (s is empty) {
            return 0
        }
    
        char head = extract first char of s
        string remainder = get rest of s without the head
        if (head == ch) {
            count = 1
        }
        return count + count_chars(remainder, ch)
    }