basics · intermediate · ~15 min

Count occurrences

Repeatedly search, advancing past each match.

Challenge

Count how many times a substring appears, without double-counting overlaps.

Task

Implement int count_occurrences(const char *hay, const char *needle) that returns the number of non-overlapping occurrences of needle in hay. After each match, resume searching just past it (advance by the needle's length). Return 0 if needle is empty. No main — the grader calls it.

Input

A NUL-terminated haystack hay and a NUL-terminated needle needle.

Output

Returns the count of non-overlapping matches, as an int.

Example

count_occurrences("banana", "ana")   ->   1     (the second "ana" overlaps, not counted)
count_occurrences("aaaa", "aa")       ->   2
count_occurrences("abc", "z")         ->   0
count_occurrences("abc", "")          ->   0

Edge cases

  • An empty needle returns 0.
  • Overlapping matches are not counted twice (e.g. "aaaa" / "aa" is 2, not 3).

Rules

  • Advance by the needle length after each match (non-overlapping).

Input format

A NUL-terminated haystack hay and needle needle.

Output format

The count of non-overlapping matches, as an int.

Constraints

Non-overlapping; an empty needle returns 0.

Starter code

#include <string.h>

int count_occurrences(const char *hay, const char *needle) {
    /* TODO */
    return 0;
}

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