Reverse a string word by word

From CodeCodex

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

Contents

[edit] C#


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

[edit] Ruby

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

[edit] Perl 5


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

[edit] Perl 6


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

[edit] Haskell


reverseWords = unwords . reverse . words

[edit] Python

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

OR

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