Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

comment on

( [id://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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (1)
As of 2024-04-25 00:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found