How To Properly Compare Strings
Updated:
In C, we can’t compare strings with == or !==. We have to use functions declared in the string.h header file. Let’s see why and how to do it.
The why
In C, a string variable is nothing more than a pointer pointing to a string literal (so, a constant string) or to a modifiable array of characters. So, if we try comparing this way:
char str_1[] = "hello";
char str_2[] = "world";
if (str_1 != str_2) {
printf("not equal\n");
} else {
printf("equal\n");
}
We get this output:
not equal
This would seem ok, but if we change str_2 and define it as a copy of str_1:
char str_1[] = "hello";
char str_2[] = "hello";
We get the same output again, which is clearly wrong:
not equal
In fact, here we are just comparing the base addresses of str_1 and str_2, so, the positions of the memory buffers containing "hello" and "world" (or "hello" and another "hello" in the second case). We are not comparing the content of the strings. So, let’s see how to do it properly.
The how
When we want to compare two strings, we have to compare the two character arrays element by element, whether they are constant or not. You can alway design your own support function to do it, but the standard way is to use the strcmp function with its variants.
int strcmp(const char *lhs, const char *rhs);
The strcmp function returns 0 if the strings are equal, a negative int if lhs appears before rhs in lexicographical order, a positive int viceversa.
So, we can fix the previous program like this:
char str_1[] = "hello";
char str_2[] = "world";
if (strcmp(str_1, str_2) != 0) {
printf("not equal\n");
} else {
printf("equal\n");
}
This time we’ll get not equal as the output when str_1[] = "hello" and str_2[] = "world". Finally, we correctly get equal as the output when str_1[] = "hello" and also str_2[] = "hello".
Missing null-termination safety
As you surely know, a C string is terminated with the special character \0, the null character. If the strings we pass as an argument to strcmp weren’t terminated for some reason, we would have a problem. In that case, strcmp would compare the memory until it finds the byte \0 in str_1 or in str_2.
When we want to avoid such a situation and set the maximum number of characters to be compared, we can use the strncmp function.
int strncmp(const char *lhs, const char *rhs, size_t count);