basics · beginner · ~15 min
Scan a string accumulating a count.
Count how many times a given character occurs in a string.
Implement int char_count(const char *s, char c) that returns the number of occurrences of the character c in the string s.
A NUL-terminated string s and a single character c.
Returns the number of positions where s equals c, as an int.
char_count("banana", 'a') -> 3
char_count("", 'x') -> 0
char_count("abc", 'z') -> 0
A NUL-terminated string s and a character c.
The number of times c appears in s, as an int.
s is a null-terminated C string. c is an ASCII character. Traversal is read-only.
int char_count(const char *s, char c) {
/* TODO */
return 0;
}
Dereferencing past the null terminator; calling strlen inside the loop causing O(N^2) complexity.
Empty string, character not present, all characters match, single-byte string.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.