在C中将以null终止的字符串与以非null终止的字符串进行比较 [英] Comparing null-terminated string with a non null-terminated string in C
问题描述
我正在使用的反序列化库(messagepack)不提供以null终止的字符串.相反,我得到了一个指向字符串开头和长度的指针.将此字符串与普通的以零结尾的字符串进行比较的最快方法是什么?
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 fastest way to compare this string to a normal null-terminated string?
推荐答案
The fastest way is strncmp()
which limits the length to be compared.
if (strncmp(sa, sb, length)==0)
...
但是,这假定您使用的长度是两个字符串的最大长度.如果以null终止的字符串的长度可能更大,则必须首先比较该长度.
This assumes however that the length you use is the maximum length of the two strings. If the null terminated string could have a bigger length, you first have to compare the length.
if(strncmp(sa,sb, length)==0 && strlen(sa)<=length) // sa being the null terminated one
...
请注意,在比较之后有意检查了strlen(),以避免在第一个字符甚至不匹配的情况下不必要地遍历null终止字符串中的所有字符.
Note that the strlen() is checked on purpose after the comparison, to avoid unnecessarily iterating through all the characters o fthe null terminated string if the first caracters don't even match.
最终的变体是:
if(strncmp(sa,sb, length)==0 && sa[length]==0) // sa being the null terminated one
...
这篇关于在C中将以null终止的字符串与以非null终止的字符串进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!