The Reversing Words Filter

Difficulty: ★ ★ ★ ☆

A few months back, this blog’s monthly Exercise was to write a filter to reverse all text input. No matter how much text floated in, the filter gobbled it all up and spewed it back in reverse order. This month’s challenge is similar, but on a smaller scale.

The challenge this month is again to write a filter. This filter also reverses text, but only one word at a time.

As a filter, the program doesn’t prompt for input; it processes standard input until the EOF (end-of-file) is encountered. This operation means that text can be typed directly at the command prompt or redirected from a file or other source. As text is input, words are output backwards:

This is text input forwards - and backwards!
sihT si txet tupni sdrawrof - dna sdrawkcab!

Due to line buffering, the backwards text output occurs after the newline is input. Otherwise, each word is output backwards, including words with numbers and containing an apostrophe:

Words with numbers abc123def
sdroW htiw srebmun fed321cba

Above, the “word” abc123def is processed and output as fed321cba.

Here’s sample output where a word with an apostrophe is processed:

Don't try this at home!
t'noD yrt siht ta emoh!

Getting the basic word-reversing algorithm down is a first step. Adding tests for numbers and apostrophes can be added later, but it’s still part of the challenge.

Try this exercise on your own before you peek at my solution.

Leave a Reply