Previous: 11.3.1 Palindromes
Up: 11.3 More Example Programs
Next: 11.3.3 Substrings
Previous Page: 11.3.1 Palindromes
Next Page: 11.3.3 Substrings

11.3.2 Words

Our next task is to break up a string into words delimited by white space.

WDS: Read strings; break up each string into its constituent words.

The algorithm starts by skipping over leading white space. If the string is not exhausted, a word starts at that position and continues until the next white space. Here is the algorithm.

while not EOF, read a string s

initialize string index to 0

while not NULL skip over leading white space initialize word index to 0

copy the next word into wd terminate word with a NULL print the word

In our algorithm, a word is any sequence of characters delimited by white space. Figure 11.14 shows the program.

It reads lines until EOF scanning each line until a NULL is reached. Each scan first skips over white space, then copies a word into a string, wd, while characters are non-white space and non-NULL. A terminating NULL is added to the word and it is printed. Here is sample session:

tep@wiliki.eng.hawaii.edu
Sat Sep 3 07:04:57 HST 1994