STRCMP()
this is used to compare two strings based on their lexicographical (dictionary) order. the comparison is based on ASCII values of characters from left to right; the first unmatched character decides the result. the function returns one of the following values:
0 if the strings are equal
A negative value if the first (left) string is less than the second (right) string
A positive value if the first (left) string is greater than the second (right) string
int strcmp(const char *str1, const char *str2);
#include <stdio.h>
#include <string.h>
int main() {
char fruit1[] = "apple";
char fruit2[] = "apricot";
// Compare the two strings lexicographically
// They match until the third character: 'p' in "apple" vs 'r' in "apricot"
// Since 'p' < 'r' in ASCII, the result is negative
int result = strcmp(fruit1, fruit2); // Returns a negative value ('p' - 'r' = 112 - 114)
// Show the comparison result
printf("Comparison result: %d\n", result); // Output: -2
return 0;
}
Last updated