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

The deserialization library (messagepack) I am using does not contain a zero-terminated string. Instead, I get a pointer to the beginning of the line and the length. What is the fastest way to compare this string with a normal zero-terminated string?

0
c string messagepack
Mar 11 '15 at 20:50
source share
3 answers

The fastest way to strncmp() , which limits the length to be compared.

  if (strncmp(sa, sb, length)==0) ... 

This assumes that the length you are using is the maximum length of two lines. If a null-terminated string can be long, you must first compare the length.

  if(strncmp(sa,sb, length)==0 && strlen(sa)<=length) // sa being the null terminated one ... 

Note that strlen () is specifically checked after comparison to avoid unnecessarily iterating over all characters of the end line if the first characters do not match.

The final version:

  if(strncmp(sa,sb, length)==0 && sa[length]==0) // sa being the null terminated one ... 
+1
Mar 11 '15 at 20:52
source share
 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; } 

using:

 ... int result; char einz[4] = "einz"; // not terminated char *zwei = "einz"; // terminated result = compare(einz, sizeof einz, zwei, strlen(zwei)); ... 
+1
Mar 11 '15 at 21:03
source share

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; } } 
+1
Mar 11 '15 at 10:29
source share



All Articles