How is the strcmp function used in C language?
The strcmp function in C language is used for comparing the size of two strings.
The function prototype is:
int strcmp(const char *str1, const char *str2);
The parameters str1 and str2 represent two strings to be compared. The function returns an integer value with several possible outcomes.
- Return 0 if str1 is equal to str2.
- Return a negative number if str1 is less than str2.
- If str1 is greater than str2, return a positive number.
The strcmp function compares the corresponding characters of two strings in dictionary order until it encounters a different character or reaches the end of both strings. During comparison, it compares the ASCII values of the characters in sequence.
For example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello";
char str2[] = "world";
int result = strcmp(str1, str2);
if (result == 0) {
printf("str1 equals to str2\n");
} else if (result < 0) {
printf("str1 is less than str2\n");
} else {
printf("str1 is greater than str2\n");
}
return 0;
}
The output result is:
str1 is less than str2
In the example above, the comparison was made between the two strings “hello” and “world”. Because “hello” is smaller than “world” in lexicographical order, a negative number was returned.