pointers-memory · intermediate · ~15 min

Implement strstr

Nested pointer iteration; corner cases of empty inputs.

Challenge

Write your own strstr: find the first place one string appears inside another.

Task

Implement const char *my_strstr(const char *haystack, const char *needle) that returns a pointer to the first occurrence of needle within haystack, or NULL if it does not appear. No main — the grader calls it.

Input

  • haystack: the NUL-terminated string to search in.
  • needle: the NUL-terminated substring to find (may be empty).

Output

A pointer into haystack at the start of the first match, or NULL if needle is not found. An empty needle returns haystack itself.

Example

my_strstr("hello world", "world")   ->   pointer to "world" (haystack+6)
my_strstr("hello world", "hello")   ->   haystack
my_strstr("hello world", "xyz")     ->   NULL
my_strstr("hello", "")              ->   haystack

Edge cases

  • Empty needle returns haystack.
  • No match returns NULL.

Rules

  • Do not call the standard strstr.

Input format

A haystack string and a needle string (needle may be empty).

Output format

Pointer to the first match in haystack, NULL if not found, haystack for an empty needle.

Constraints

Do not call the standard strstr.

Starter code

#include <stddef.h>

const char *my_strstr(const char *haystack, const char *needle) {
    /* TODO */
    return NULL;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.