basics · intermediate · ~15 min

Index of a substring

Locate a substring within a string.

Challenge

Implement int index_of(const char *hay, const char *needle) returning the index of the first occurrence of needle in hay, or -1 if not found. An empty needle matches at 0.

Starter code

#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.