How to compare between string in C++

In this article, we are going to learn how to compare two strings in C++ language. After the user enters the two strings to be compared we can use the strcmp() function which is available in the string.h library to compare them. It can return three different values based on the comparison:

  1. Zero: If the strings to be compared are equal then 0 is returned by the function. This implies that all the characters in the entered string are the same.
  2. Lesser than zero: When the first non-matching character in string one has ASCII value lesser than that of its corresponding character in string two, then a value <0 is returned by the function.
  3. Greater than zero: When the first non-matching character in string one has ASCII value greater than that of its corresponding character in string two, then a value >0 is returned by the function.

Compare between string in C++

Let’s take the help of an example.

Input:

String 1: awesome

String 2: awesoem

Output:

The entered strings are not equal

Code Implementation:

#include <iostream>
#include <string.h> 
using namespace std;

int main()
{
    char str1[50], str2[50];
    cout<<"Enter string1 : ";
    cin>>str1; 
    cout<<"Enter string2 : ";
    cin>>str2; 
    if(strcmp(str1, str2)==0)
    {
        cout<<"The entered strings are equal";
    }
    else
    {
        cout<<"The entered strings are not equal";
    }

    return 0;
}

 

Working:

Here, the strcmp() function begins with comparing the first character of each of the given string. In case it is equal to the other string, it continues the comparison with the other pairs until the characters differ between the given strings or until a terminating null-character is encountered.

I hope, you have understood how our program works to compare two strings in C++ language.

Mention below your comments, if you find any mistake in the article or to share more information related to the topic of this article.

You may also learn,

Leave a Reply

Your email address will not be published. Required fields are marked *