Character Utilities

When we write programs to work with characters, it might be useful to have some utility functions and macros to determine the class of a character.

For example, we might like to test to see if a character is a digit character; e.g. '0' or '1', etc. Looking at the ASCII table, we can see that the ASCII code for all of the digits are adjacent in value. For example, the code for '0' is 48, '1' is 49, .... '9' is 57. So to test if a character is a digit character, we can test if it is in the range between '0' and '9' (48 to 57). We can define a macro for such an expression:

     #define   IS_DIGIT(c)   ((c) >= '0' && (c) <= '9')

Similarly, we can write a macro that tests if a character is a lower case alphabetic character:

     #define   IS_LOWER(c)   ((c) >= 'a' && (c) <= 'z')

or an upper case letter:
     #define   IS_UPPER(c)   ((c) >= 'A' && (c) <= 'Z')

It might also be useful to test if a character is a white space character:
     #define   IS_WHITE_SPACE(c)   ((c) == ' ' || (c) == '\t' || (c) == '\n')

or simply a printable character:
     #define   IS_PRINT(c)   ((c) >= 32 && (c) < 127)

amoung others.

We can group all these character testing macros together, with other macros and prototypes for other character routines into a single header file. Here is chrutil.h. We will find this header file, and the associated source file for these functions, quite useful in programs we will write when we need to deal with characters.

For example, how can we modify the count program to count the number of lines, as well as the number of characters in the input?

The code is in count3.c. Counting words is a bit trickier, and is described in the text and here.
[up] to Overview.