Comparing String objects using Relational Operators in C++


Here we will see how to compare two strings in C++. The C++ has string class. It also has the compare() function in the standard library to compare strings. But here we will use the conditional operators like ==, !=, <, >, <=, >=. These operators check the strings character by characters. Let us see the code to get better idea.

Example

 Live Demo

#include<iostream>
using namespace std;
void compareStrings(string s1, string s2) {
   if (s1 != s2)
      cout << s1 << " is not equal to "<< s2 << endl;
   else if(s1 == s2)
      cout << "Strings are equal";
   if (s1 > s2)
      cout << s1 << " is greater than "<< s2 << endl;
   else if(s1 < s2)
      cout << s2 << " is greater than "<< s1 << endl;
}
int main() {
   string s1("hello");
   string s2("helLo");
   compareStrings(s1, s2);
}

Output

hello is not equal to helLo
hello is greater than helLo

Updated on: 17-Dec-2019

321 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements