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

C++Server Side ProgrammingProgramming

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
raja
Published on 15-Feb-2018 17:18:12
Advertisements