In this article we will discuss how to compare strings using strcmp().

strcmp() is a C Library function that helps to compare two strings i.e. char *

It iterates over both strings i.e. firstStr & secondStr in parallel and compares each character lexicographically until it finds NULL or ‘\0’ in any of the string.

Also, strcmp() compares string in case sensitive manner.

Its defined in following header file

What strcmp() returns :

  • 0   : If both strings are exactly equal.
  • <0 : If ASCII value of first mismatch character in firstStr is less than corresponding character in secondStr.
  • >0 : If ASCII value of first mismatch character in secondStr is less than corresponding character in firstStr.

Compare if two strings are equal using strcmp()

Suppose we have two strings i.e.

Now check if both strings are equal using strcmp()

Output:

Here, strcmp() returned 0 because both the strings were exactly same.

Now, lets create a new string i.e.

Now we have two different strings, Now check if both strings are not equal using strcmp() i.e.

Output:

 

Here strcmp() returned 1 because ASCII value of first mismatch character in str2 is less than corresponding character in str1.

Complete example is as follows,

Output:

To Compile the above example in Linux Use following command,

g++ example.cpp

 

Click Here to Subscribe for more Articles / Tutorials like this.