Simon Richter
Simon Richter

Reputation: 29586

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?

Upvotes: 2

Views: 994

Answers (3)

Mad Physicist
Mad Physicist

Reputation: 114230

You can use the strncmp approach and check for a NUL terminator in s1:

!strncmp(s1, s2, s2_len) && !s1[s2_len]

Upvotes: 2

wildplasser
wildplasser

Reputation: 44230

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)

Upvotes: 4

Marco Bonelli
Marco Bonelli

Reputation: 69276

If strncmp(s1, s2, s2_len) returns 0 you know that s1 is at least as long as s2, so you can just do a check for the terminator to exclude the possibility that s2 is a prefix of s1:

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

Upvotes: 2

Related Questions