basics · intermediate · ~15 min
Compare a bounded number of leading characters.
Decide whether one string starts with another.
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.
A NUL-terminated string s and a candidate prefix pre.
Returns 1 if s starts with pre, otherwise 0.
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)
s cannot match.A NUL-terminated string s and a candidate prefix pre.
1 if s starts with pre, otherwise 0.
The empty prefix always matches.
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.