C String Comparison: A Guide to strcmp() Function
In C language, you can use the strcmp() function to compare the size of two strings.
The prototype for the strcmp() function is as follows:
int strcmp(const char *s1, const char *s2);
The function takes two pointers as parameters, representing two strings to be compared. It will return an integer value indicating the relationship in size between the two strings.
If the return value is 0, it means that the two strings are equal; if the return value is less than 0, it means that the first string is less than the second string; if the return value is greater than 0, it means that the first string is greater than the second string.
The following is an example code using the strcmp() function to compare the size of strings:
#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("The first string is smaller.\n");
}
else
{
printf("The second string is smaller.\n");
}
return 0;
}
Running the above code will output “The first string is smaller.” because the string “Hello” is smaller than the string “World”.