Home > Net >  Strict Weak Ordering of "i" and "Love"
Strict Weak Ordering of "i" and "Love"

Time:10-17

Assumption:: a < b returns true when a precedes b.

Code

std::string a = "i";
std::string b = "Love";
std::cout << "(a < b) = " <<  ((a < b) ? "true" : "false");

Output

(a < b) = false 

We know "i" preceedes "Love" so why is the above code return false?
Is my initial assumption wrong?
Help is appreciated thanks.

CodePudding user response:

In ASCII uppercase come earlier than lowercase. You can print its values by std::cout << (int)'L' << ' ' << (int)'i';

CodePudding user response:

Lowercase “l” has a higher character code than uppercase “L” in the character encoding your C implementation uses. Most C implementations currently use ASCII for the characters A-Z and a-z. In ASCII, the code for “L” is 76, and the code for “i” is 105.

To see the codes your C implementation uses for characters, you can convert them to int and print them. Here is an example using a character constant:

std::cout << static_cast<int>('i') << '\n'; // Will print 105 in implementations that use ASCII.

For string literals and strings generally, you can select individual characters using subscripts:

std::cout << static_cast<int>("Love"[0]) << '\n'; // Will print 76 in implementations that use ASCII.

When you want to compare individual characters ignoring case, you can use toupper or tolower (declared in <cctype>) to convert both characters to the same case for comparison:

std::cout << (tolower(a[0]) < tolower(b[0]) ? "true" : "false") << '\n';

To do this for strings, you may need to write additional code; I am not aware of a case-insensitive string compare in the standard C library.

CodePudding user response:

Other users have already pointed out that in most common character encodings (i.e.: ASCII and Unicode), lower-case letter i does not precede upper-case letter L. Read more about ASCII and the difference between lower- and upper-case letters.

I'd like to add that if you want to perform a comparison without caring about letter case (so that i precedes L like you want), you can make use of specific functions like POSIX-compliant strcasecmp(). See also other methods to compare strings ignoring the case.

  • Related