basics · intermediate · ~15 min
Repeatedly search, advancing past each match.
Count how many times a substring appears, without double-counting overlaps.
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.
A NUL-terminated haystack hay and a NUL-terminated needle needle.
Returns the count of non-overlapping matches, as an int.
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
"aaaa" / "aa" is 2, not 3).A NUL-terminated haystack hay and needle needle.
The count of non-overlapping matches, as an int.
Non-overlapping; an empty needle returns 0.
#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.