Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Comment on

( #3333=superdoc: print w/ replies, xml ) Need Help??

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.


In reply to Five Ways to Reverse a String of Words (C#, Perl 5, Perl 6, Ruby, Haskell) by eyepopslikeamosquito

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others making s'mores by the fire in the courtyard of the Monastery: (8)
    As of 2014-10-02 00:53 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      What is your favourite meta-syntactic variable name?














      Results (41 votes), past polls