basics · intermediate · ~15 min

Count occurrences

Repeatedly search, advancing past each match.

Challenge

Implement int count_occurrences(const char *hay, const char *needle) returning the number of non-overlapping occurrences of needle in hay. Return 0 if needle is empty.

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.