Reverse a string word by word

From CodeCodex

Revision as of 17:37, 18 February 2011 by 79.91.219.32 (Talk)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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

Tcl

package require struct::list
proc reverseWords s {return [struct::list reverse [split $s]]}