Similar to how we can sort numbers, strings can also be sorted (by alphabet.) The C string library provides help for doing so via the strcmp function. This function compares two strings and returns a negative number, zero or a positive number depending on which of the two strings comes first in the alphabet.
Here is how the function works: strcmp compares the two strings character by character. If the first character of two strings is equal, the next character of two strings are compared. This continues until the corresponding characters of the two strings are different or a null character โ\0โ is reached. Here is the return value of the function:
So if you compare "Hello" with "hello", what would strcmp() return? Use the code window below to look at a bunch of examples and really understand the function.
Compile and run the code below in your own C environment.
#include <stdio.h>
#include <string.h>
int main(void) {
char name1[] = "Petra";
char name2[] = "Karin";
/* try other words such as fool and foolish, thrill and thrifty, lastname and Lastname, etc. */
int val;
val = strcmp(name1, name2);
printf("Comparing %s to %s yields val = %d.\n", name1, name2, val);
if (val<0) {
printf("%s comes before %s in the alphabet.\n", name1, name2);
} else if (val>0) {
printf("%s comes after %s in the alphabet.\n", name1, name2);
} else if (val==0) {
printf("%s and %s are equal.\n", name1, name2);
}
return 0;
}