7.13. string
s are comparableΒΆ
All the comparison operators that work on int
s and double
s
also work on strings
.
Take a look at the active code below, which checks to see if word
is
equal to "banana"
.
The other comparison operations are useful for putting words in alphabetical order.
The active code below 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.
- 1
- Both match up to the g but Dog is shorter than Doghouse so it comes first in the dictionary.
- 0
- Strings are compared character by character.
Q-3: What would the result of the following comparison be?
Where 1
means true and 0
means false.
"Dog" < "Doghouse";
- 1
- d is greater than D
- 0
- 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.
Q-4: What would the result of the following comparison be?
Where 1
means true and 0
means false.
"dog" < "Dog";
- 1
- d is greater than D.
- 0
- The length does not matter. Lower case d is greater than upper case D.
Q-5: What would the result of the following comparison be?
Where 1
means true and 0
means false.
"dog" < "Doghouse";
- 1
- They are equal so one can't be greater than the other.
- 0
- Correct! because they are equal. They are equal because all characters match.
Q-6: What would the result of the following comparison be?
Where 1
means true and 0
means false.
"bread" < "bread";