The strcmp() function compares two strings and returns an integer value based on the result.
C strcmp() function declaration
int strcmp(const char *str1, const char *str2)
str1 – The first string
str2 – The second string
Return value of strcmp()
This function returns the following values based on the comparison result:
- 0 if both the strings are equal
- >0 if the ASCII value of first unmatched character of string str1 is greater than the character in string str2
- <0 if the ASCII value of first unmatched character of string str1 is less than the character in string str2
According to many online tutorials this function returns positive value when the first string is greater than second string, which is absolutely not true or you can say not phrased correctly, because when we say that one string is greater than second we are talking in terms of length. However this function doesn’t compare length, it matches the ASCII value of each character of first string with the second string and returns positive if the ASCII value of first unmatched character in first string is greater than the ASCII value of the unmatched character of second string
Lets take an example to understand this.
Example: strcmp() function in C
#include <stdio.h> #include <string.h> int main () { char str1[20]; char str2[20]; int result; //Assigning the value to the string str1 strcpy(str1, "hello"); //Assigning the value to the string str2 strcpy(str2, "hEllo"); result = strcmp(str1, str2); if(result > 0) { printf("ASCII value of first unmatched character of str1 is greater than str2"); } else if(result < 0) { printf("ASCII value of first unmatched character of str1 is less than str2"); } else { printf("Both the strings str1 and str2 are equal"); } return 0; }
Output:
ASCII value of first unmatched character of str1 is greater than str2
In the above example, we are comparing two strings str1 and str2 using the function strcmp(). In this case the strcmp() function returns a value greater than 0 because the ASCII value of first unmatched character ‘e’ is 101 which is greater than the ASCII value of ‘E’ which is 69.
Leave a Reply