In this tutorial, we will Compare Strings Using strcmp() function in C. But if you want to learn more about String you may go through the following topic in C.
strcmp() function is used to compare two string to each other and returns an integer value.
The syntax for strcmp() in c:
strcmp(first_string, second_string);
- returns 0: if both the string are equal.
- returns negative integer: if string1 < string2
- returns positive integer: if string1 > string2
The header file string.h
defines the strcmp()
function.
Let us understand through an example of strcmp function in C programming.
String comparison using strcmp() function in C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | //C Program to Compare Two Strings using strcmp() #include <stdio.h> #include <string.h> int main() { char str1[20], str2[20]; int result; printf("Enter a first string: "); gets(str1); printf("Enter a second string: "); gets(str2); //use of strcmp result = strcmp(str1, str2); //displaying the result if (result == 0) printf("Strings are same"); else printf("Strings are not same"); return 0; } |
Output:
Enter a first string: This is simple2code
Enter a second string: This is simple2code
Strings are same
str1
and str2
takes the input for the two strings from the user and the result variable stores the value after comparison of two strings. And the final result is displayed accordingly.