Search code examples
cc-standard-library

Compare string of unknown length against string of known length


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?


Solution

  • if (!strncmp(s1, s2, s2_len) && s1[s2_len] == 0) {...}
    

    If the strncmp() returns zero, then s2 is a prefix of s1.

    • if s1[s2_len] is NUL, then the strings are equal
    • when not: then strlen(s1) > s2_len
    • if the strncmp() returns nonzero, the second test is skipped (short-cicuit evaluation)