strlcmp
jul, 2008
problem:
partial string match
solution:
int strlcmp(const char *s1, const char *s2) {
//compare 2 strings ignoring differences in length
if (!s1 || !s2) return true;
char c1, c2;
do {
//need to ensure the last 2 compared chars are in the correct values
c1 = *s1++;
c2 = *s2++;
} while (c1 && c1 == c2);
//if both c1 and c2 are non-zero it means that:
//the end of the strings was not met before a difference was found
//thus return the difference
// < 0 indicates that c1 < c2 and s1 < s2
// > 0 indicates that c1 > c2 and s1 > s2
//however, if one or both of the chars is zero
//it indicates that the end of one or both of the strings was met
//so return zero indicating that the strings (ignoring length) are equal
//note that a > A and thus a > B
return (c1 && c2 ? c1 - c2 : 0);
}
return value
0 - strings are the same up to the length of the shortest
negative - s1 is less than s2 (same return as strcmp)
positive - s1 more than s2 (same return as strcmp)