The Program in C that compares two strings when user gives an input is given below:
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100];
printf("Enter first string: ");
scanf("%s", str1);
printf("Enter second string: ");
scanf("%s", str2);
int result = strcmp(str1, str2);
if (result == 0) {
printf("The strings are equal.\n");
} else if (result < 0) {
printf("The first string is less than the second string.\n");
} else {
printf("The first string is greater than the second string.\n");
}
return 0;
}
Output:
Enter first string: 23
Enter second string: 56
The first string is less than the second string.
Pro-Tips💡
This program uses the scanf
function to read in two strings from the user, and stores them in the str1
and str2
variables.
It then uses the strcmp
function to compare the contents of str1
and str2
.
The strcmp
function returns 0 if the strings are equal, a negative value if the first string is lexicographically less than the second string, and a positive value if the first string is lexicographically greater than the second string.
The program then uses an if-else statement to determine the result of the comparison and print the appropriate message.
You can also use the strncmp()
function which is similar to strcmp()
but allows you to specify the maximum number of characters to compare. This can be useful to prevent buffer overflow.
int result = strncmp(str1, str2, sizeof(str1));
This function compares the first sizeof(str1)
characters of str1
and str2
.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.