register
[username]

strlicmp

jul, 2008

problem:

partial case insensitive string match

solution:

int strlicmp(const char *s1, const char *s2) {
	//compare 2 strings ignoring differences in length
	//case insensitive
	//e.g. "" == "test", "te" == "tEst"
	//a-A = 97-65 = 32
	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 && toupper(c1) == toupper(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 therefore convert to upper case
	return (c1 && c2 ? toupper(c1) - toupper(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 strcasecmp)
positive - s1 more than s2 (same return as strcasecmp)

tags:

Visual C++; c++; partial match