basics · beginner · ~15 min

Count a character in a string

Scan a string accumulating a count.

Challenge

Count how many times a given character occurs in a string.

Task

Implement int char_count(const char *s, char c) that returns the number of occurrences of the character c in the string s.

Input

A NUL-terminated string s and a single character c.

Output

Returns the number of positions where s equals c, as an int.

Example

char_count("banana", 'a')   ->   3
char_count("", 'x')         ->   0
char_count("abc", 'z')      ->   0

Edge cases

  • A character that never appears (or an empty string) gives 0.

Input format

A NUL-terminated string s and a character c.

Output format

The number of times c appears in s, as an int.

Constraints

s is a null-terminated C string. c is an ASCII character. Traversal is read-only.

Starter code

int char_count(const char *s, char c) {
    /* TODO */
    return 0;
}

Common mistakes

Dereferencing past the null terminator; calling strlen inside the loop causing O(N^2) complexity.

Edge cases to handle

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.