Difference between revisions of "Reverse a string word by word"

From CodeCodex

(Erlang)
(Implementations)
Line 54: Line 54:
 
   s.split.reverse.join(' ')
 
   s.split.reverse.join(' ')
 
end
 
end
 +
</pre>
 +
 +
===Ruby===
 +
<pre class="tcl">
 +
package require struct::list
 +
proc reverseWords s {return [struct::list reverse [split $s]]}
 
</pre>
 
</pre>
  
Line 63: Line 69:
 
[[Category:Python]]
 
[[Category:Python]]
 
[[Category:Ruby]]
 
[[Category:Ruby]]
 +
[[Category:Tcl]]

Revision as of 17:37, 18 February 2011

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

Ruby

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