Differences Between C++ String and Compare



In C++ we can compare two strings using compare() function and the == operator. Then the question is why there are two different methods? Is there any difference or not? Yes, there are some basic differences between compare() and == operator.

In C++ the == operator is overloaded for the string to check whether both strings are same or not. If they are the same this will return 1, otherwise 0. So it is like Boolean type function.

The compare() function returns two different things. If both are equal, it will return 0, If the mismatch is found for character s and t, and when s is less than t, then it returns -1, otherwise when s is larger than t then it returns +1. It checks the matching using the ASCII code.

Let us see an example to get the idea of the above discussion.

Example Code

In the example code below, we will compare two strings using both the == operator and the compare() function to see the differences in their behavior.

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

int main() {
    string str1 = "apple";
    string str2 = "apple";
    string str3 = "banana";

    // Using '==' operator
    if (str1 == str2) {
        cout << "str1 is equal to str2 using '=='" << endl;
    } else {
        cout << "str1 is not equal to str2 using '=='" << endl;
    }

    if (str1 == str3) {
        cout << "str1 is equal to str3 using '=='" << endl;
    } else {
        cout << "str1 is not equal to str3 using '=='" << endl;
    }

    // Using compare() function
    int result = str1.compare(str2);
    if (result == 0) {
        cout << "str1 is equal to str2 using compare()" << endl;
    } else if (result < 0) {
        cout << "str1 is less than str2 using compare()" << endl;
    } else {
        cout << "str1 is greater than str2 using compare()" << endl;
    }

    result = str1.compare(str3);
    if (result == 0) {
        cout << "str1 is equal to str3 using compare()" << endl;
    } else if (result < 0) {
        cout << "str1 is less than str3 using compare()" << endl;
    } else {
        cout << "str1 is greater than str3 using compare()" << endl;
    }

    return 0;
}

The output of the above code will be:

str1 is equal to str2 using '=='
str1 is not equal to str3 using '=='
str1 is equal to str2 using compare()
str1 is less than str3 using compare()
Farhan Muhamed
Farhan Muhamed

No Code Developer, Vibe Coder

Updated on: 2025-05-26T18:17:37+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements