Parse and Count Words in a String

This month’s Exercise is based on code presented in the June 1 Lesson: split a string into separate words. The difference is that each word you pluck from the string is followed by the number of letters in that word.

The code you concoct must churn through a string, identifying when a word starts and stops. When the end of the word is encountered, the number letters in the word is output.

Here’s the sample string to parse, a quote from Mark Twain:

char string[] = "Training is everything. The peach was once a bitter almond; cauliflower is nothing but cabbage with a college education.\nMark Twain\n";

The program’s output looks something like this:

Training 8
is 2
everything 10
The 3
peach 5
was 3
once 4
a 1
bitter 6
almond 6
cauliflower 11
is 2
nothing 7
but 3
cabbage 7
with 4
a 1
college 7
education 9
Mark 4
Twain 5

Each word in the string appears on a line by itself, followed the letters in the word.

As was done in the June 1 Lesson, separator characters are skipped over; blank lines are not output.

Please try this Exercise on your own before you peek at my solution.

Leave a Reply