< previous page page_522 next page >

Page 522
Programming Techniques
What kinds of things can we do with character data in a program? The possibilities are endless and depend, of course, on the particular problem we are solving. But several techniques are so widely used that it's worth taking a look at them.
Comparing Characters
In previous chapters, you have seen examples of comparing characters for equality. We have used tests such as
if (ch == a)
and
while (inputChar != \n)
Characters can also be compared by using <, <=, >, and >=. For example, if the variable firstLetter contains the first letter of a person's last name, we can test to see if the last name starts with A through Hby using this test:
if (firstLetter > = A && firstLetter <= H)
On one level of thought, a test like this is reasonable if you think of < as meaning comes before in the character set and > as meaning comes after. On another level, the test makes even more sense when you consider that the underlying representation of a character is an integer number. The machine literally compares the two integer values using the mathematical meaning of less than or greater than.
When you write a logical expression to check whether a character lies within a certain range of values, you sometimes have to keep in mind the character set your machine uses. In Chapter 8, we hinted that a test like
if (ch >= a && ch <= z)
works correctly on some machines but not on others. In ASCII, this If test behaves correctly because the lowercase letters occupy 26 consecutive positions in the character set. In EBCDIC, however, there is a gap between the lowercase letters i and j that includes nonprintable characters, and there is another gap between rand s. (There are similar gaps between the uppercase letters I and J and between R and S. If your machine uses EBCDIC, you must rephrase the If test to be sure you include only the desired characters. A better approach, though, is to take advantage of the is functions supplied by the standard library through the header file ctype.h. If you replace the above If test with this one:

 
< previous page page_522 next page >