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;
}
Off-by-one in low/high boundary updates; integer overflow in (low + high) / 2 instead of low + (high - low) / 2; infinite loop when bounds don't progress.
Empty array; target element not present; target at index 0 or index len-1; array with all identical elements.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.