Difference between Relational operator(==) and std::string::compare() in C++


There is only one difference between the relational operator == and std::string::compare(). That is the return value. Internally, string::operator==() is using string::compare()

Relational operator(==) returns a boolean just signifying whether the 2 strings are equal or not while compare returns an integer that signifies how the strings relate to each other.

To elaborate on the use cases, compare() can be useful if you're interested in how the two strings relate to one another (less or greater) when they happen to be different. For example,

Example

#include <iostream>
using namespace std;
int main() {
   string s1 = "Tutorials Point";
   string s2 = "Hello World";
   cout << s1 == s2;
   cout << s1.compare(s2);
   cout << s2.compare(s1);
   return 0;
}

Output

This will give the output −

0
1
-1

Updated on: 11-Feb-2020

223 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements