Comparing Strings in C++

The relational operators <, <=, >, >= test whether one string is less than, less than or equal, greater than, or greater than or equal to another:


#include <iostream>

using namespace std;
// system namespace
int main() 
    string big = "big", small = "small";
    string s1 = big;    // s1 is a copy of big
    if (big == small)   // false
    cout<<"Both are equal";
     if (big <= s1) // true, they're equal, so big is less than or equal to s1
         cout<<"big is smaller than small";

	return 0;


big is smaller than small

The relational operators compare strings using the same strategy as in a (case-sensitive) dictionary:

  1. If two strings have different lengths and if every character in the shorter string is equal to the corresponding character of the longer string, then the shorter string is less than the longer one.
  2. If the characters in two strings differ, then we compare them by comparing the first character at which the strings differ.

You may also like...