basics · intermediate · ~15 min

Prefix check

Compare a bounded number of leading characters.

Challenge

Decide whether one string starts with another.

Task

Implement int has_prefix(const char *s, const char *pre) that returns 1 if s begins with the string pre, else 0. Every character of pre must match the corresponding character at the start of s. The empty prefix always matches. No main — the grader calls it.

Input

A NUL-terminated string s and a candidate prefix pre.

Output

Returns 1 if s starts with pre, otherwise 0.

Example

has_prefix("hello", "he")      ->   1
has_prefix("hello", "lo")      ->   0
has_prefix("hello", "")        ->   1     (empty prefix matches)
has_prefix("hi", "hello")      ->   0     (prefix longer than s)

Edge cases

  • The empty prefix matches any string.
  • A prefix longer than s cannot match.

Input format

A NUL-terminated string s and a candidate prefix pre.

Output format

1 if s starts with pre, otherwise 0.

Constraints

The empty prefix always matches.

Starter code

int has_prefix(const char *s, const char *pre) {
    /* TODO */
    return 0;
}

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