Text Parsing Power – Solution

This month’s Exercise hosts a realm of possible solutions. So I present you with my three solutions, two of which are general and one specific.

My first two solutions use an array to store the start of each word in the sentence: The sentence is scanned front-to-back. I use the isalpha() function to test for word boundaries. When a word is found, its location in the string is saved.

After all the words are located, a loop works backwards through the array of stored locations, with each word displayed in reverse order.

That’s the general approach to my first two solutions. Why two? One uses pointers and the other uses array notation. They both behave in the same way.

Click here to view the pointer solution.

Click here to view the array solution.

My third solution is a kludge. It doesn’t bother to store the start of each word. Instead, text input is scanned backwards. Spaces are replaced by null characters (\0). When a word boundary is found, that word is displayed, the string is truncated again, then the scanning continues to the start of the string.

Click here to view the backwards-scanning solution.

Additional solutions are possible. As I wrote in the Exercise post, library functions can help you parse a string of text. Next Saturday’s Lesson offers a solution that uses the strtok() function. Later this month, I’ll post a solution that uses the strsep() function.

Leave a Reply