In this post, you will learn how to compare two strings using C language. There is a function strcmp() available in core C. It accepts two string parameters and returns an integer value and if the value is 0 then both the strings are equal otherwise not equal.
Let’s see the C program to compare two strings using strcmp(str1, str2):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <stdio.h> int main() { char str1[100], str2[100]; //get the strings from the user printf("First String: "); scanf("%s", &str1); printf("Second String: "); scanf("%s", &str2); if ( strcmp(str1,str2) == 0 ) { printf("Both the strings are equal!"); } else { printf("Both the strings are not equal!"); } return 0; } |
Sample Output of the above program is:
1 2 3 4 5 6 |
First String: test Second String: one Both the strings are not equal! -------------------------------- Process exited after 5.922 seconds with return value 0 Press any key to continue . . . |
I hope this would have helped you to learn how to compare strings using C language.