From Tux
Revision as of 10:13, 12 January 2018 by Williams (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

This page exists to test Wiki markup without modifying useful public pages. Please only modify the page below this.

Relational operators with string

It's clear that expressions like a > 5 when a is an int or double are unambiguous both to human eyes and to the compiler. We can also use these relational operators to compare the string datatype as well, although it's not immediately clear what makes one string greater than or less than another. However, in C++ the behavior of relational operators on strings is well defined.

Let s1 and s2 both be strings, then for any expression involving a relational operator the strings are evaluated left-to-right, char-by-char, examining the ASCII value of each char. If all chars in one string are at the beginning of the other string, they are not equal, but the shorter string is defined to be less than the longer string.


if ( "Test" == "test" )    // false: 'T' and 't' are different chars
if ( "Test" < "test")      // true: 'T' is ASCII code 84, 't' is ASCII code 116
if ( "Test" >= "Testing" ) // false: "Test" exactly matches the first 4 chars of "Testing", 
                           //        so the shorter string is considered less than the longer one
if ( "Test" > "Tess")      // false: The first three characters of each are identical, 
                           //        but for the fourth 't' is ASCII code 116, 's' is ASCII code 117