Programming in C

(Barry) #1
Variable-Length Character Strings 213

Ta b le 10.1 Execution of the countWordsFunction


i string[i] wordCount lookingForWord
0 true
0 'W' 1 false
1 'e' 1 false
2 'l' 1 false
3 'l' 1 false
4 ',' 1 true
5' '1 true
6 'h' 2 false
7 'e' 2 false
8 'r' 2 false
9 'e' 2 false
10 ' ' 2 true
11 'g' 3 false
12 'o' 3 false
13 'e' 3 false
14 's' 3 false
15 '.' 3 true
16 '\0' 3 true

The Null String


Now consider a slightly more practical example of the use of the countWordsfunction.
This time, you make use of your readLinefunction to allow the user to type in multiple
lines of text at the terminal window.The program then counts the total number of
words in the text and displays the result.
To make the program more flexible, you do not limit or specify the number of lines
of text that are entered.Therefore, you must have a way for the user to “tell” the pro-
gram when he is done entering text. One way to do this is to have the user simply press
the Enter (or Return) key an extra time after the last line of text has been entered.
When the readLinefunction is called to read in such a line, the function immediately
encounters the newline character and, as a result, stores the null character as the first (and
only) character in the buffer.Your program can check for this special case and can know
that the last line of text has been entered after a line containing no characters has been
read.
A character string that contains no characters other than the null character has a spe-
cial name in the C language; it is called the null string.When you think about it, the use
of the null string is still perfectly consistent with all of the functions that you have
defined so far in this chapter.The stringLengthfunction correctly returns 0 as the size

Free download pdf