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.

Starter code

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

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.