http://qs321.pair.com?node_id=589260

Recently, the C# programmers at work have been asking job applicants to write a function to reverse a string of words. For example, given an input string of:

" one two three four "
the function should produce:
"four three two one"
That is, the input string reversed word by word, with a single space between each word and with no leading or trailing space. You may assume the input string consists only of alphabetic characters, spaces and tabs.

A popular C# approach goes something like:

private static string reverseWords(string str) { string[] words = Array.FindAll<string>(str.Split( new char[] {' ','\t'}), delegate(string s) { return !String.IsNullOrEmpty(s); }); int i = words.Length - 1; if (i < 0) return String.Empty; StringBuilder sb = new StringBuilder(words[i]); while (--i >= 0) sb.Append(' ').Append(words[i]); return sb.ToString(); }
Though the C# programmers seemed happy with this solution, it's a bit too verbose for my personal taste. When I suggested replacing all the StringBuilder claptrap with:
Array.Reverse(words); return String.Join(" ", words);
they surprised me by saying they preferred the former version because StringBuilder was "faster" (though I couldn't measure any significant difference in running time).

Anyway, this little episode provoked me into solving their little problem in other, er, less verbose languages.

In Perl 5, I whipped up:

sub reverseWords { join ' ', reverse split(' ', shift) }
after a few seconds thought, then pondered a Perl 6 version:
sub reverseWords(Str $s) returns Str { $s.words.reverse.join(' ') }
which resembles a Ruby version:
def reverseWords(s) s.split.reverse.join(' ') end
Finally, this Haskell version:
reverseWords = unwords . reverse . words
may well be the winner of a multi-language golf competition. ;-)

Though one artificial little program proves nothing, at least I've had the satisfaction of demonstrating that this little problem can be easily solved as a one liner in many languages.

Please feel free to improve any of these solutions and/or add a new version in a language of your choice.

References

Acknowledgements: I'd like to thank the friendly folks at Haskell-Cafe for helping me with the Haskell version.

Updated 13-dec: Changed from split to comb in accordance with latest S29, which specifies that split no longer has a default delimiter and advises you instead to comb the words out of the string when splitting on whitespace. Updated 6-oct-2008: Added References section. Updated 10-0ct-2010. Changed comb to words, thanks moritz.