Reverse a string word by word

From CodeCodex

Revision as of 01:39, 3 December 2010 by 211.2.129.92 (Talk)

Related content:

Reverses a string word by word, as opposed to character by character.

Implementations

C#

private static string reverseWords(string str) {
     string[] words = str.Split(' ');
     Array.Reverse(words);
     return String.Join(" ", words);
}

Erlang

reverseWords(S) ->
    string:join( lists:reverse( string:tokens(S, " ") ), " " ).

Haskell

reverseWords = unwords . reverse . words

Perl 5

 sub reverseWords {
     join ' ', reverse split(' ', shift)
 }

Perl 6

 sub reverseWords(Str $s) returns Str {
     $s.comb.reverse.join(' ')
 }

Python

def reverseWords(s):
    return ' '.join(reversed(s.split(' ')))

OR

def reverseWords(s):
    return ' '.join(s.split(' ')[::-1])

Ruby

def reverseWords(s)
  s.split.reverse.join(' ')
end