Comparing String objects using Relational Operators in C++

If strings are compared using relational operators then, their characters are compared lexicographically according to the current character traits, means it starts comparison character by character starting from the first character until the characters in both strings are equal or a NULL character is encountered.

List of Relational Operators:

Important Conditions:

  1. s1 A string s1 is smaller than s2 string, if either, length of s1 is shorter than s2 or first mismatched character is smaller.
  2. s1 > s2 : A string s1 is greater than s2 string, if either, length of s1 is longer than s2 or first mismatched character is larger.
  3. <= and >= have almost same implementation with additional feature of being equal as well.
  4. If after comparing lexicographically, both strings are found same, then they are said to be equal.
  5. If any of the points from 1 to 3 follows up then, strings are said to be unequal.

// CPP code to implement relational 
// operators on String objects
using namespace std;
void relational_operation(string s1, string s2)
    string s3 = s1 + s2;
    if(s1 != s2)
        cout << s1 << " is not equal to " << s2 << endl;
    if(s1 > s2)
        cout << s1 << " is greater than " << s2 << endl;
    else if(s1 < s2)
        cout << s1 << " is smaller than " << s2 << endl;
    if(s3 == s1 + s2)
        cout << s3 << " is equal to " << s1 + s2 << endl;
// Main function
int main()
    string s1("Geeks");
    string s2("forGeeks");
    relational_operation(s1, s2);
  return 0; 


Geeks is not equal to forGeeks
Geeks is smaller than forGeeks
GeeksforGeeks is equal to GeeksforGeeks

This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks (We know you do!) and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

Article Tags :
Practice Tags :