In C language, strings can be compared with each other using the strcmp() function. This function compares two strings alphabetically and returns a value based on the comparison result.
In this program, the user enters two strings. The strcmp() function compares both strings. If the first string is greater than the second string, it displays that the first string is greater; otherwise, it displays that the second string is greater.
How It Works?
str1 and str2 to store strings.strcmp() function.k.k > 0, then the first string is greater.#include <stdio.h> #include <conio.h> #include <string.h> main() { char str1[20], str2[20]; int k; clrscr(); printf("Enter First String : "); scanf("%s", str1); printf("\nEnter Second String : "); scanf("%s", str2); k = strcmp(str1, str2); if(k > 0) { printf("\nFirst String is greater"); } else { printf("\nSecond String is greater"); } getch(); }
strcmp() function.strcmp() function and understand the comparison result.strcmp() to compare both strings. If the returned value is less than 0, the first string is smaller; otherwise, the second string is smaller.#include <stdio.h> #include <conio.h> #include <string.h> main() { char str1[20], str2[20]; int k; clrscr(); printf("Enter First String : "); scanf("%s", str1); printf("\nEnter Second String : "); scanf("%s", str2); k = strcmp(str1, str2); if(k < 0) { printf("\nFirst String is Smaller"); } else { printf("\nSecond String is Smaller"); } getch(); }
strcmp() function. If the return value is less than 0, the first string comes before the second string alphabetically. Otherwise, the second string is smaller.