Examples of strcmp() in C
Example 1. strcmp() behavior for identical strings
This program illustrates the behavior of the strcmp() function for identical strings.
C
// C program to illustrate // strcmp() function #include<stdio.h> #include<string.h> int main() { char first_str[] = "g f g" ; char second_str[] = "g f g" ; // Using strcmp() int res = strcmp (first_str, second_str); if (res==0) printf ( "Strings are equal" ); else printf ( "Strings are unequal" ); printf ( "\nValue returned by strcmp() is: %d" , res); return 0; } |
Output
Strings are equal Value returned by strcmp() is: 0
Example 2. strcmp() behavior for the lexicographically greater first string
The below example demonstrates the strcmp() function behavior for the lexicographically greater first string.
C
// C program to illustrate // strcmp() function #include<stdio.h> #include<string.h> int main() { // z has greater ASCII value than g char first_str[] = "zfz" ; char second_str[] = "gfg" ; int res = strcmp (first_str, second_str); if (res==0) printf ( "Strings are equal" ); else printf ( "Strings are unequal" ); printf ( "\nValue of result: %d" , res); return 0; } |
Output
Strings are unequal Value of result: 19
Example 3. strcmp() behavior for the lexicographically smaller first string.
The below example demonstrates the strcmp() function behavior for the lexicographically smaller first string.
C
// C program to illustrate // strcmp() function #include<stdio.h> #include<string.h> int main() { // b has less ASCII value than g char first_str[] = "bfb" ; char second_str[] = "gfg" ; int res = strcmp (first_str, second_str); if (res==0) printf ( "Strings are equal" ); else printf ( "Strings are unequal" ); printf ( "\nValue returned by strcmp() is: %d" , res); return 0; } |
Output
Strings are unequal Value returned by strcmp() is: -5
C strcmp()
In C language, the <string.h> header file contains the Standard String Library that contains some useful and commonly used string manipulation functions. In this article, we will see how to compare strings in C using the function strcmp().
Contact Us