Parse and Count Words in a String – Solution

The key to making this month’s Exercise work isn’t to know when a word stops, but when the separator characters stop. That’s because words aren’t always separated by single characters.

My solution builds upon the second code example presented in the June 1 Lesson. In fact, the only major change is the addition of the count variable, which tallies the characters in a word:

#include <stdio.h>
#include <ctype.h>

int main()
{
    char string[] = "Training is everything. The peach was once a bitter almond; cauliflower is nothing but cabbage with a college education.\nMark Twain\n";
    int count,x,y;

    x = count = 0;
    while( string[x] )
    {
        switch( string[x] )
        {
            case ' ':
            case '.':
            case ',':
            case '!':
            case '?':
            case ';':
            case ':':
            case '\n':
                printf(" %d\n",count);
                count = 0;
                y = 1;
                while(string[x+y])
                {
                    if( !isalpha(string[x+y]) )
                        y++;
                    else
                        break;
                }
                x+=y;
            default:
                count++;
                putchar( string[x] );
        }
        x++;
    }

    return(0);
}

Variable count is initialized to zero, along with variable x, at Line 9.

In the switch-case structure, if a separator character isn’t encountered, the default condition reigns, and the count variable is incremented (Line 34).

The separator character triggers the count variable to be output at Line 22. Its value is reset to zero (Line 23), and the code loops until the start of the next alphabetic character.

My solution works well on the sample string. In the wild, if this code is run on a word that begins with a number, the results are inaccurate. The code can be modified to deal with such a situation, as well as handle quoted text and other possibilities. If you want to make such modifications, feel free to do so.

I hope your solution met with success and successfully output the word length values. Keep in mind that your solution need not look exactly like mine. As long as the code compiles with no errors or warnings, the output is accurate and looks good, and you’re satisfied, congratulations.

Leave a Reply