|Problems? Is your data what you think it is?|
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:
the function should produce:
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:
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:
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:
after a few seconds thought, then pondered a Perl 6 version:
which resembles a Ruby version:
Finally, this Haskell version:
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.
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.