Skip to main content

How To Think Like a Computer Scientist C++ Edition The Pretext Interactive Version

Section 7.13 strings are comparable

All the comparison operators that work on ints and doubles also work on strings.
Listing 7.13.1. This active code checks to see if word is equal to "banana".
The other comparison operations are useful for putting words in alphabetical order.
Listing 7.13.2. This active code uses comparison operators to determine the ordering of word relative to "banana".
You should be aware, though, that the string class does not handle upper and lower case letters the same way that people do. All the upper case letters come before all the lower case letters. As a result,
Your word, Zebra, comes before banana.
A common way to address this problem is to convert strings to a standard format, like all lower-case, before performing the comparison. The next sections explains how. I will not address the more difficult problem, which is making the program realize that zebras are not fruit.
For the following questions, remember that in C++ 1 means true and 0 means false.

Checkpoint 7.13.1.

What would the result of the following comparison be? Where 1 means true and 0 means false.
"Dog" < "Doghouse";
  • Both match up to the g but Dog is shorter than Doghouse so it comes first in the dictionary.
  • Strings are compared character by character.

Checkpoint 7.13.2.

What would the result of the following comparison be? Where 1 means true and 0 means false.
"dog" < "Dog";
  • d is greater than D
  • Yes, upper case is less than lower case according to the ordinal values of the characters.
  • They are the same word
  • C++ is case sensitive meaning that upper case and lower case characters are different.

Checkpoint 7.13.3.

What would the result of the following comparison be? Where 1 means true and 0 means false.
"dog" < "Doghouse";
  • d is greater than D.
  • The length does not matter. Lower case d is greater than upper case D.

Checkpoint 7.13.4.

What would the result of the following comparison be? Where 1 means true and 0 means false.
"bread" < "bread";
  • They are equal so one can’t be greater than the other.
  • Correct! because they are equal. They are equal because all characters match.
You have attempted 1 of 4 activities on this page.