Check if two strings are equal in C++

This tutorial will discuss about unique ways to check if two strings are equal in C++.

Technique 1: Using == Operator

We can directly apply the == operator on two string objects, to confirm if these two string objects are equal or not. By equal, we mean the both the string objects contains the same characters in same alphabetical order. It will compare the characters in stings one by one.

Let’s see the complete example,

#include <iostream>
#include <string>

int main()
{
    std::string strValue1 = "Testing";
    std::string strValue2 = "Testing";

    // check if two strings are equal
    if (strValue1 == strValue2)
    {
        std::cout << "Yes, two strings are equal." << std::endl;
    }
    else
    {
        std::cout << "No, two strings are not equal." << std::endl;
    }

    return 0;
}

Output :

Yes, two strings are equal.

Technique 2: Using strcmp() function

Suppose we have two char arrays instead of string objects, and we want to confirm that the strings in these two char arrays are equal or not. We can use the strcmp() function from the cstring header file. It accepts two strings (char pointers or char arrays) as argument and return zero if both the strings are equal (contains the smlar characters), then it will return zero. If first string is less than the second string in alphabetical order, then it will return a negative value. where as, if first string is greater than the second string in alphabetical order, then it will return a value greater than zero. But important point is: If both strings are equal then it will return zero.

Let’s see the complete example,

#include <iostream>
#include <cstring>

int main()
{
    char strValue1[] = "Testing";
    char strValue2[] = "Testing";

    // check if two strings are equal
    if (std::strcmp(strValue1, strValue2) == 0)
    {
        std::cout << "Yes, two strings are equal." << std::endl;
    }
    else
    {
        std::cout << "No, two strings are not equal." << std::endl;
    }

    return 0;
}

Output :

Yes, two strings are equal.

Summary

Today we learned about several ways to check if two strings are equal in C++. Thanks.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top