[英]Count the number of times a letter occurs in a word(string) in c using recursion
这是我在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");
这将起作用:
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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.