What is the library function for string comparison in the C language?
In the C language, the library function used to compare strings is `strcmp()`. It compares the contents of two strings and returns an integer value to indicate the result of the comparison.
The declaration of the `strcmp()` function is as follows:
int strcmp(const char *str1, const char *str2);
The function takes in two parameters of type `const char*`, which are the two strings to be compared.
The meaning of the return value of the function is as follows:
If `str1` is equal to `str2`, return 0.
If `str1` is less than `str2`, a negative number (usually -1) will be returned.
If `str1` is greater than `str2`, it will return a positive number (usually 1).
For example, the following code demonstrates how to compare two strings using the `strcmp()` function.
#include <stdio.h>#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
int result = strcmp(str1, str2);
if (result == 0) {
printf("The strings are equal\n");
} else if (result < 0) {
printf("%s is less than %s\n", str1, str2);
} else {
printf("%s is greater than %s\n", str1, str2);
}
return 0;
}
The output will be `Hello is less than World`, because the letter “H” has a lower value in the ASCII code than “W”.