I am implementing a lexicographic sort and my professor told us to use strcmp
in our implementation. The problem is, strcmp
is very confusing in respects to how it compares strings.
For instance, this here yields false:
if (strcmp("What", "am") > 0) {
printf("true\n");
} else {
printf("false\n");
}
Isn't "What" suppose to be greater than "am" lexicographically? The man page is very spartan in terms of explaining how the function determines if one string is greater or less than the other. There are some questions here, but I still cannot determine this result based on those explanations.
The problem is that strcmp makes a binary comparison. This fact makes the function case sensitive! The ASCII code of "W" is smaller than the ASCII code of "a".
The way to solve the problem is to compare text strings that as the same capitalization.
A simple way to obtain this shall be:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
char* stoupper( char* s )
{
char* p = s;
while (*p) {
*p= toupper( *p ); p++
};
return s;
}
int main(void)
{
char a[10];
char b[10];
strcpy(a,"What");
strcpy(b,"am");
if (strcmp(stoupper(a), stoupper(b)) > 0) {
printf("true\n");
} else {
printf("false\n");
}
}
Remember that the use of the function stoupper modifies definitively the text in the string!