How to compare the size of strings in the C language?
In C language, string comparison can be achieved using the strcmp function. The prototype of the strcmp function is:
int strcmp(const char *str1, const char *str2);
This function compares two strings, str1 and str2, and returns a negative integer if str1 is smaller than str2, a positive integer if str1 is larger than str2, and 0 if str1 is equal to str2.
Here is an example code comparing the size of two strings:
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[20] = "World";
int result = strcmp(str1, str2);
if (result < 0) {
printf("str1 is less than str2\n");
} else if (result > 0) {
printf("str1 is greater than str2\n");
} else {
printf("str1 is equal to str2\n");
}
return 0;
}
The output is:
str1 is less than str2