Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do < and > on C++ strings reflect alphabetical ordering?

Tags:

c++

string

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.
like image 667
yrazlik Avatar asked Mar 04 '13 23:03

yrazlik


People also ask

Which function is used to sort the strings in alphabetical order in C?

Master C and Embedded C Programming- Learn as you go User has to enter number of names, and those names are required to be sorted in alphabetical order with the help of strcpy() function.

Which function is used to sort the string in alphabetical order?

The elements of an array are sorted using the sort() method. The sort() method sorts the strings in alphabetical and ascending order.

Which comes first in alphabetical order?

The standard order of the modern ISO basic Latin alphabet is: A-B-C-D-E-F-G-H-I-J-K-L-M-N-O-P-Q-R-S-T-U-V-W-X-Y-Z. An example of straightforward alphabetical ordering follows: As; Aster; Astrolabe; Astronomy; Astrophysics; At; Ataman; Attack; Baa.

Can you compare strings alphabetically in C++?

Strings have a comparison operator. This isn't actually alphabetical. String comparison is done by binary value.


2 Answers

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.

like image 173
Pete Becker Avatar answered Nov 11 '22 22:11

Pete Becker


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).

like image 35
Joseph Mansfield Avatar answered Nov 11 '22 20:11

Joseph Mansfield