这是我在 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/