basics · intermediate · ~15 min
Locate a substring within a string.
Find where one string first appears inside another.
Implement int index_of(const char *hay, const char *needle) that returns the 0-based index of the first occurrence of needle within hay, or -1 if needle does not occur. An empty needle matches at index 0. No main — the grader calls it.
A NUL-terminated haystack hay and a NUL-terminated needle needle.
Returns the index of the first match, or -1 if not found.
index_of("hello world", "world") -> 6
index_of("abc", "ab") -> 0
index_of("abc", "") -> 0 (empty needle)
index_of("abc", "xy") -> -1
A NUL-terminated haystack hay and needle needle.
The 0-based index of the first match, or -1 if not found.
An empty needle matches at index 0.
#include <string.h>
int index_of(const char *hay, const char *needle) {
/* TODO */
return -1;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.