Comparing null-terminated string with a non null-terminated string in C

后端 未结 3 834
渐次进展
渐次进展 2021-01-25 02:46

The deserialization library (messagepack) I am using does not provide null-terminated strings. Instead, I get a pointer to the beginning of the string and a length. What is the

3条回答
  •  闹比i
    闹比i (楼主)
    2021-01-25 03:28

    Here is one way:

    bool is_same_string(char const *s1, char const *s2, size_t s2_len)
    {
        char const *s2_end = s2 + s2_len;
        for (;;)
        {
            if ( s1[0] == 0 || s2 == s2_end )
                return s1[0] == 0 && s2 == s2_end;
    
            if ( *s1++ != *s2++ )
                return false;
        }
    }
    

提交回复
热议问题