Differences between C++ string == and compare() in C++

In this tutorial, we will be able to find the difference between compare function and == operator with some easy examples.

Definition and working of compare() and == operator in C++

string::compare(): It returns an integer. It checks that two string is smaller, greater or equals.

Let two string be s and t. Then compare function will return,

  1. zero if s and t are equal.
  2. less than zero if s is less than t.
  3. greater than zero is s is greater than t.

Header file used:

#include<bits/stdc++.h>

 

Input:

string s,t;
cout<<"ENTER FIRST STRING ";
getline(cin,s);
cout<<"ENTER SECOND STRING ";
getline(cin,t);

Algorithm:

if((s.compare(t))==0)
std::cout<<"both string are same";
else if((s.compare(t))<0)
std::cout<<"s is smaller than t";
else
std::cout<<"s is greater than t";

Complete code:

#include<bits/stdc++.h>
using namespace std;
int main()
 {
    string s,t; 
    cout<<"ENTER FIRST STRING "; 
   getline(cin,s); 
   cout<<"ENTER SECOND STRING "; 
   getline(cin,t);
   if((s.compare(t))==0)
   std::cout<<"Both string are same";
   else if((s.compare(t))<0)
   std::cout<<"s is smaller than t";
   else
   std::cout<<"s is greater than t";
   
   return 0;
}

EXPLANATION:

This code takes two input s and t as string format. Then by using the compare function, it checks that if s and t are equal, s is smaller than t or s is greater than t.

output 1:

ENTER FIRST STRING apple 
ENTER SECOND STRING mango 
s is smaller than t

output 2:

ENTER FIRST STRING apple
ENTER SECOND STRING apple
both strings are same

output 3:

ENTER FIRST STRING mango
ENTER SECOND STRING apple
s is greater than t

 

operator::==() : It returns a boolean (0 or 1). It only checks that two string is equal or not.

Let two string be s and t. The will return,

  1. zero if s and t are unequal.
  2. one if s and t are equal.

Header file :

#include<bits/stdc++.h>

Input:

string s,t; 
cout<<"ENTER FIRST STRING "; 
getline(cin,s); 
cout<<"ENTER SECOND STRING "; 
getline(cin,t);

Algorithm:

if(s==t)
std::cout<<"Both string are same";
else 
std::cout<<"The two string are not same ";

Complete code:

#include<bits/stdc++.h>
using namespace std;
int main()
 {
     string s,t; 
     cout<<"ENTER FIRST STRING "; 
     getline(cin,s); 
   cout<<"ENTER SECOND STRING "; 
   getline(cin,t);
     if(s==t)                     
     std::cout<<"Both string are same";   
   else 
   std::cout<<"Two string are not same ";  
   
   return 0;
}

EXPLANATION:

This code takes two input s and t as string format. then == operator only checks that s and t are equal or not. If both are equal then it will go in the yes part otherwise in else part.

Output 1 :

ENTER FIRST STRING apple
ENTER SECOND STRING mango
Two string are not same

Output 2:

ENTER FIRST STRING apple
ENTER SECOND STRING apple
two string are not same

Also read: C++ time() function with example

Leave a Reply