basics · beginner · ~15 min

Count characters

Iterate a C string until the null terminator.

Challenge

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

Task

Implement int count_char(const char *s, char c) that returns the number of occurrences of c in the NUL-terminated string s. No main — the grader calls it.

Input

  • s: a NUL-terminated string (may be empty).
  • c: the character to count.

Output

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

Example

count_char("banana", c) where c='a'   ->   3
count_char("banana", c) where c='n'   ->   2
count_char("hello",  c) where c='z'   ->   0

Edge cases

  • Empty string returns 0.
  • A character not present returns 0.

Why this matters

Counting how many times a character appears in a string is the simplest 'iterate and accumulate' pattern. It's the unit of building histograms, frequency tables, and search counts.

Input format

A NUL-terminated string s and a character c.

Output format

The count of c in s, as an int.

Constraints

s is a null-terminated C string (never NULL in tests). c is a valid ASCII character. Read-only traversal.

Starter code

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

Common mistakes

Forgetting to terminate the loop on the null terminator; modifying the input string.

Edge cases to handle

Empty string "", string with no occurrences of c, string where every character is c, c is null terminator.

Complexity

O(n).

Background lessons

Up next

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