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?

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

 Live Demo

#include <iostream>
using namespace std;

int main() {
   string str1 = "Hello";
   string str2 = "Help";
   string str3 = "Hello";

   cout << "Comparing str1 and str2 using ==, Res: " << (str1 == str2) << endl;//0 for no match
   cout << "Comparing str1 and str3 using ==, Res: " << (str1 == str3) << endl;//1 for no match

   cout << "Comparing str1 and str2 using compare(), Res: " << str1.compare(str2) << endl;//checking smaller and greater
   cout << "Comparing str1 and str3 using compare(), Res: " << str1.compare(str3) << endl;//0 for no match
}

Output

Comparing str1 and str2 using ==, Res: 0
Comparing str1 and str3 using ==, Res: 1
Comparing str1 and str2 using compare(), Res: -1
Comparing str1 and str3 using compare(), Res: 0

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements