我正在使用的反序列化库(messagepack)不提供以null结尾的字符串。相反,我会得到一个指向字符串开头和长度的指针。比较这个字符串与普通的以null结尾的字符串的最快方法是什么?
strncmp()
函数,该函数限制了要进行比较的长度。 if (strncmp(sa, sb, length)==0)
...
if(strncmp(sa,sb, length)==0 && strlen(sa)<=length) // sa being the null terminated one
...
if(strncmp(sa,sb, length)==0 && sa[length]==0) // sa being the null terminated one
...
strncmp
相等,则可以。但是,如果非以空字符结尾的字符串可能包含嵌入的空字符,你仍然可能遇到问题。 - undefinedbool 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;
}
}
int compare(char *one, size_t onelen, char *two, size_t twolen)
{
int dif;
dif = memcmp(one, two, onelen < twolen ? onelen : twolen);
if (dif) return dif;
if (onelen == twolen) return 0;
return onelen > twolen? 1 : -1;
}
使用方法:
...
int result;
char einz[4] = "einz"; // not terminated
char *zwei = "einz"; // terminated
result = compare(einz, sizeof einz, zwei, strlen(zwei));
...
return onelen - twolen;
。顺便说一下,你的使用场景需要太多次遍历,因为你总是要通过遍历以空字符结尾的字符串来获取其长度...;-) - undefined
memcmp()
函数比较字符串的内容。 - undefined