Programming in C

(Barry) #1

214 Chapter 10 Character Strings


of the null string; your concatfunction also properly concatenates “nothing” onto the
end of another string; even your equalStringsfunction works correctly if either or
both strings are null (and in the latter case, the function correctly calls these strings
equal).
Always remember that the null string does, in fact, have a character in it, albeit a
null one.
Sometimes, it becomes desirable to set the value of a character string to the null
string. In C, the null string is denoted by an adjacent pair of double quotation marks. So,
the statement
char buffer[100] = "";
defines a character array called bufferand sets its value to the null string. Note that the
character string ""is notthe same as the character string " "because the second string
contains a single blank character. (If you are doubtful, send both strings to the
equalStringsfunction and see what result comes back.)
Program 10.8 uses the readLine,alphabetic,and countWordsfunctions from previ-
ous programs.They have not been shown in the program listing to conserve space.

Program 10.8 Counting Words in a Piece of Text
#include <stdio.h>
#include <stdbool.h>

/***** Insert alphabetic function here *****/

/***** Insert readLine function here *****/

/***** Insert countWords function here *****/

int main (void)
{
char text[81];
int totalWords = 0;
int countWords (const char string[]);
void readLine (char buffer[]);
bool endOfText = false;

printf ("Type in your text.\n");
printf ("When you are done, press 'RETURN'.\n\n");

while (! endOfText )
{
readLine (text);

if ( text[0] == '\0' )
endOfText = true;
Free download pdf