BouncyKnight
BouncyKnight

Reputation: 47

How do the ">" and "<" operators work for string comparisons?

In the C++ textbook I'm reading (Programming, Principles and Practice using C++ by Bjarne Stroustrup), there are numerous instances of code snippets in which strings are compared as follows: if (str1 > str2) and then some code.

Could someone please explain to me how "bigger than" and "less than" operators work in conjunction with strings declared as follows:

#include <string>
.
.
.
string str1 = "foo";
string str2 = "bar";

I've tried searching on Stack Overflow and on others for this answer, but to no avail.

Upvotes: 2

Views: 117

Answers (2)

HolyBlackCat
HolyBlackCat

Reputation: 96013

Relational operators on strings estabilish so-called lexicographical order. It's the same ordering as used in the dictionaries.

Here's the algorithm: to determine if a is less than b, you need to find the smallest i so that a[i] != b[i], and if (unsigned char)a[i] < (unsigned char)b[i], then a < b, otherwise a > b.

If there is no such i, then a == b.

If a is a prefix of b, then a < b (this follows from the algorithm above, if you consider the extra \0 at the end of a string to be a part of the string).

Upvotes: 3

Abhishek Bhagate
Abhishek Bhagate

Reputation: 5766

The strings are compared lexicographically . The string in which an character is lexicographically greater than the corresponding character in other string will be considered as the greater string. This is known as lexicographical comparison.

The lexicographic or lexicographical order (also known as lexical order, dictionary order, alphabetical order or lexicographic(al) product) is a generalization of the way words are alphabetically ordered based on the alphabetical order of their component letters.

You can use the .compare() method as well to compare two strings . It will return the following values -

0 : They compare equal

Less than 0 : Either the value of the first character that does not match is lower in the compared string, or all compared characters match but the compared string is shorter.

more than 0 : Either the value of the first character that does not match is greater in the compared string, or all compared characters match but the compared string is longer.

On the contrary, the relational operators (like >, <, ==) will return only boolean values true of false. In the expression str1 < str2 , str1 will be smaller than str2 if first mismatched character in str1 is smaller than the corresponding character in str2. If all characters match, str1 will be less than str2 only if its length is shorter.

Upvotes: 4

Related Questions