0

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

#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");
4

2 回答 2

1

这将起作用:

int count_chars(const char* string, char ch) {
  return *string? count_chars(string + 1, ch) + (ch == *string) : 0;
}
于 2013-10-11T04:00:20.310 回答
0

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

  1. 基本情况(停止递归)
  2. 减少的输入集(从原来的减少,以便实际达到基本情况)

你的函数看起来像这样(在伪代码中)

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)
}
于 2013-10-11T04:02:35.773 回答