I want to compare a null-terminated string of an unknown length (s1
) with an unterminated string of a known length (s2
).
!strncmp(s1, s2, s2_len)
is close to correct, but also becomes evaluates to true if s2
is a prefix of s1
.
strlen(s1) == s2_len && !strcmp(s1, s2)
is correct, but scans s1
twice.
Obviously, manually comparing the strings also works, but loses me all the shiny optimizations the C library has picked up in the last forty years.
Is there a good way to achieve this with C library functions?
if (!strncmp(s1, s2, s2_len) && s1[s2_len] == 0) {...}
If the strncmp()
returns zero, then s2
is a prefix of s1
.
s1[s2_len]
is NUL, then the strings are equalstrlen(s1) > s2_len
strncmp()
returns nonzero, the second test is skipped (short-cicuit evaluation)