Count a Character
Completed
Write int count_char(char *s, char c). Read a line and a character, and print how many times it appears.
Input
Line 1: text. Line 2: one character.
Output
The count.
Example
Input
mississippi river s
Output
4
Editor
C
Hints
Move the pointer itself with s++ instead of using an index.
Solution explanation
The parameter s is a local copy of the pointer, so moving it doesn't affect the caller.
Show solution
#include <stdio.h>
#include <string.h>
int count_char(char *s, char c) {
int n = 0;
while (*s != '\0') {
if (*s == c) n++;
s++;
}
return n;
}
int main() {
char s[200], c;
fgets(s, 200, stdin);
s[strcspn(s, "\n")] = '\0';
scanf(" %c", &c);
printf("%d\n", count_char(s, c));
return 0;
}