7

I have a question about alphabetical order of strings in C++. Let us say i have two strings:

    string x="asd123";
    string y="asd136";


Can we compare these strings with < or > operators? For example: can we say

    if(x>y)
    cout<<".....";

Does that always work? Thanks.
djechlin
  • 59,258
  • 35
  • 162
  • 290
yrazlik
  • 10,411
  • 33
  • 99
  • 165

2 Answers2

14

The strings are compared lexicographically (dictionary style), with a string that's a shorter subset of another string coming before the longer one. But it's not necessarily alphabetical; it's according to the underlying character encoding. Most systems these days use ASCII, so lowercase letters come out in order, and uppercase characters come out in order, and uppercase characters come before lowercase characters.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • 2
    A-Z letters. Non-English "special" characters, such as å, ä, ö, ń, ǹ, í, ì, é, è, ë, and lots of other similar things do not sort at all well without further work. – Mats Petersson Mar 04 '13 at 23:21
9

Yes, comparing std::strings with std::string::operator> always works. The strings are compared lexicographically. This means that each corresponding element of the two strings is compared in turn until two are found that are not equal, and that ordering determines the order of the strings.

The lexicographic ordering performs < on each element of the std::basic_string. That is, for a std::string, each char will be compared using <. It will simply compare the values of those chars. As far as C++ is concerned, a char is just a numeric value. These values are mapped to the characters in a string literal by the execution character set (which, for a modern C++ compiler, is almost always at least ASCII compatible).

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
  • 1
    @pst: `string` is a collection of bytes, not of characters. Comparison is by byte value. No free lunch. – Kerrek SB Mar 04 '13 at 23:10
  • @sftrabbit: MSVC, one of the biggest compilers, [does not default to UTF8](http://stackoverflow.com/questions/688760/how-to-create-a-utf-8-string-literal-in-visual-c-2008) – Mooing Duck Mar 04 '13 at 23:15
  • @MooingDuck Thanks - I'm not very familiar with MSVC. – Joseph Mansfield Mar 04 '13 at 23:17
  • 2
    @MooingDuck - an implementation can't use UTF8 for `std::string`, because `char_traits` is **required** to implement `eq` and `lt` to give the same results as `==` and `<`. – Pete Becker Mar 04 '13 at 23:36