Phrase reversals: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎{{header|Ring}}: Marked incorrect)
m (added whitespace before the TOC (table of contents).)
Line 12: Line 12:
* [[Reverse a string]]
* [[Reverse a string]]
* [[Reverse words in a string]]
* [[Reverse words in a string]]
<br><br>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==

Revision as of 02:48, 13 April 2016

Task
Phrase reversals
You are encouraged to solve this task according to the task description, using any language you may know.

Given a string of space separated words containing the following phrase:

"rosetta code phrase reversal"
  1. Reverse the string.
  2. Reverse each individual word in the string, maintaining original string order.
  3. Reverse the order of each word of the phrase, maintaining the order of characters in each word.

Show your output here.

See also



AutoHotkey

<lang AutoHotKey>var = ( Rosetta Code Phrase Reversal )

array := strsplit(var, " ")

loop, % array.maxindex() string .= array[array.maxindex() - A_index + 1] . " "

loop, % array.maxindex() { m := array[A_index] array2 := strsplit(m, "") Loop, % array2.maxindex() string2 .= array2[array2.maxindex() - A_index + 1] string2 .= " " }

array := strsplit(string, " " )

loop, % array.maxindex() { m := array[A_index] array3 := strsplit(m, "") Loop, % array3.maxindex() string3 .= array3[array3.maxindex() - A_index + 1] string3 .= " " }

MsgBox % var . "`n" . string3 . "`n" . String . "`n" . string2 ExitApp

esc::ExitApp</lang>

Output:
Rosetta Code Phrase Reversal
lasreveR esarhP edoC attesoR  
Reversal Phrase Code Rosetta 
attesoR edoC esarhP lasreveR 

Ada

To split a string into words, the package "Simple_Parse" from another task [[1]] is used.

<lang Ada><with Ada.Text_IO, Simple_Parse;

procedure Phrase_Reversal is

  function Reverse_String (Item : String) return String is
     Result : String (Item'Range);
  begin
     for I in Item'range loop
        Result (Result'Last - I + Item'First) := Item (I);
     end loop;
     return Result;
  end Reverse_String;
  
  function Reverse_Words(S: String) return String is
     Cursor: Positive := S'First;
     Word: String := Simple_Parse.Next_Word(S, Cursor);
  begin
     if Cursor > S'Last then -- Word holds the last word 

return Reverse_String(Word);

     else

return Reverse_String(Word) & " " & Reverse_Words(S(Cursor .. S'Last));

     end if;
  end Reverse_Words;
  
  function Reverse_Order(S: String) return String is
     Cursor: Positive := S'First;
     Word: String := Simple_Parse.Next_Word(S, Cursor);
  begin
     if Cursor > S'Last then -- Word holds the last word 

return Word;

     else

return Reverse_Order(S(Cursor .. S'Last)) & " " & Word;

     end if;
  end Reverse_Order;
  
  Phrase: String := "rosetta code phrase reversal";
  use Ada.Text_IO;

begin

  Put_Line("0. The original phrase:       """ & Phrase & """");
  Put_Line("1. Reverse the entire phrase: """ & Reverse_String(Phrase) & """");
  Put_Line("2. Reverse words, same order: """ & Reverse_Words(Phrase) & """");
  Put_Line("2. Reverse order, same words: """ & Reverse_Order(Phrase) & """");

end Phrase_Reversal;</lang>

Output:
0. The original phrase:       "rosetta code phrase reversal"
1. Reverse the entire phrase: "lasrever esarhp edoc attesor"
2. Reverse words, same order: "attesor edoc esarhp lasrever"
2. Reverse order, same words: "reversal phrase code rosetta"

ALGOL 68

Works with: ALGOL 68G version Any - tested with release 2.8.win32

<lang algol68># reverses the characters in str from start pos to end pos # PROC in place reverse = ( REF STRING str, INT start pos, INT end pos )VOID:

   BEGIN
       INT fpos := start pos, epos := end pos;
       WHILE fpos < epos
       DO
           CHAR c      := str[ fpos ];
           str[ fpos ] := str[ epos ];
           str[ epos ] := c;
           fpos       +:= 1;
           epos       -:= 1
       OD
   END; # in place reverse #

STRING original phrase := "rosetta code phrase reversal";

STRING whole reversed  := original phrase; in place reverse( whole reversed, LWB whole reversed, UPB whole reversed );

  1. reverse the individual words #

STRING words reversed := original phrase; INT start pos  := LWB words reversed;

WHILE

   # skip leading spaces #
   WHILE IF start pos <= UPB words reversed
         THEN words reversed[ start pos ] = " "
         ELSE FALSE
         FI
   DO start pos +:= 1
   OD;
   start pos <= UPB words reversed

DO

   # have another word, find it #
   INT end pos := start pos;
   WHILE IF end pos <= UPB words reversed
         THEN words reversed[ end pos ] /= " "
         ELSE FALSE
         FI
   DO end pos +:= 1
   OD;
   in place reverse( words reversed, start pos, end pos - 1 );
   start pos := end pos + 1

OD;

  1. reversing the reversed words in the same order as the original will #
  2. reverse the order of the words #

STRING order reversed := words reversed; in place reverse( order reversed, LWB order reversed, UPB order reversed );

print( ( original phrase, ": whole reversed -> ", whole reversed, newline

      , original phrase, ": words reversed -> ", words reversed, newline
      , original phrase, ": order reversed -> ", order reversed, newline
      )
)</lang>
Output:
rosetta code phrase reversal: whole reversed -> lasrever esarhp edoc attesor
rosetta code phrase reversal: words reversed -> attesor edoc esarhp lasrever
rosetta code phrase reversal: order reversed -> reversal phrase code rosetta

AppleScript

AppleScript has a very small and patchy library of primitive functions. To accumulate a larger and more coherent library, which includes some higher order functions, we can try to overcome two architectural weaknesses: 1. Built-in functions have a different type from user functions, and 2. user functions are second class properties of (first class) script objects.

Here is a simple illustration of unifying (and elevating) the function type by wrapping the built-in functions in user handlers (perhaps making some of them polymorphic where needed), and also obtaining first class status for ordinary user handler functions by 'lifting' them (for use as arguments in higher order functions) into a first class script object. (This process can be inlined, or abstracted out to an mReturn or mInject function).

<lang AppleScript>on run {}

   set phrase to "rosetta code phrase reversal"
   
   unlines({¬
       _reverse(phrase), ¬
       unwords(map(_words(phrase), _reverse)), ¬
       unwords(_reverse(_words(phrase))) ¬
           })

end run

-- Text -> Text on _reverse(xs)

   if class of xs is text then
       return (reverse of characters of xs) as text
   else
       return reverse of xs
   end if

end _reverse

-- Text -> Text on _words(str)

   return words of str

end _words

-- [a] -> (a -> b) -> [b] on map(xs, f)

   set mf to mReturn(f)
   set lst to {}
   set lng to length of xs
   repeat with i from 1 to lng
       set end of lst to mf's call(item i of xs, i, xs)
   end repeat
   return lst

end map

-- lift 2nd class function into 1st class wrapper -- handler function --> first class script object on mReturn(f)

   script mf
       property call : f
   end script

end mReturn

-- [Text] -> Text on unlines(lstLines)

   intercalate(linefeed, lstLines)

end unlines

-- [Text] -> Text on unwords(lstWords)

   intercalate(space, lstWords)

end unwords

-- Text -> Text -> [Text] on splitOn(strDelim, strMain)

   set {dlm, my text item delimiters} to {my text item delimiters, strDelim}
   set lstParts to text items of strMain
   set my text item delimiters to dlm
   return lstParts

end splitOn

-- Text -> [Text] -> Text on intercalate(strText, lstText)

   set {dlm, my text item delimiters} to {my text item delimiters, strText}
   set strJoined to lstText as text
   set my text item delimiters to dlm
   return strJoined

end intercalate</lang>

Output:
"lasrever esarhp edoc attesor
attesor edoc esarhp lasrever
reversal phrase code rosetta"

AWK

<lang awk># Usage: awk -f phrase_revers.awk function rev(s, del, n,i,a,r) {

  n = split(s, a, del)
  r = a[1]
  for(i=2; i <= n; i++) {r = a[i] del r }    
  return r

}

BEGIN {

 p0 = "Rosetta Code Phrase Reversal"
 fmt = "%-20s: %s\n"
 printf( fmt, "input",               p0 )
 printf( fmt, "string reversed",     rev(p0, "") )
 wr = rev(p0, " ")
 printf( fmt, "word-order reversed", wr )
 printf( fmt, "each word reversed",  rev(wr) )

}</lang>

Output:
input               : Rosetta Code Phrase Reversal
string reversed     : lasreveR esarhP edoC attesoR
word-order reversed : Reversal Phrase Code Rosetta
each word reversed  : attesoR edoC esarhP lasreveR

Batch File

<lang dos>@echo off setlocal enabledelayedexpansion %=== The Main Thing... ===% set "inp=Rosetta Code phrase reversal" call :reverse_string "!inp!" rev1 call :reverse_order "!inp!" rev2 call :reverse_words "!inp!" rev3 cls echo.Original: !inp! echo.Reversed: !rev1! echo.Reversed Order: !rev2! echo.Reversed Words: !rev3! pause>nul exit /b 0 %=== /The Main Thing... ===%

%=== Reverse the Order Function ===%

reverse_order

set var1=%2 set %var1%=&set word=&set str1=%1

process1

for /f "tokens=1,*" %%A in (%str1%) do (set str1=%%B&set word=%%A) set %var1%=!word! !%var1%!&set str1="!str1!" if not !str1!=="" goto process1 goto :EOF %=== /Reverse the Order Function ===%

%=== Reverse the Whole String Function ===%

reverse_string

set var2=%2 set %var2%=&set cnt=0&set str2=%~1

process2

set char=!str2:~%cnt%,1!&set %var2%=!char!!%var2%! if not "!char!"=="" set /a cnt+=1&goto process2 goto :EOF %=== /Reverse the Whole String Function ===%

%=== Reverse each Words Function ===%

reverse_words

set var3=%2 set %var3%=&set word=&set str3=%1

process3

for /f "tokens=1,*" %%A in (%str3%) do (set str3=%%B&set word=%%A) call :reverse_string "%word%" revs set %var3%=!%var3%! !revs!&set str3="!str3!" if not !str3!=="" goto process3 set %var3%=!%var3%:~1,1000000! goto :EOF %=== /Reverse each Words Function ===%</lang>

Output:
Original:       Rosetta Code phrase reversal
Reversed:       lasrever esarhp edoC attesoR
Reversed Order: reversal phrase Code Rosetta
Reversed Words: attesoR edoC esarhp lasrever

Bracmat

This example only works correctly with strings only consisting of byte-sized characters. <lang bracmat>( "rosetta code phrase reversal":?text & rev$!text:?output1 & get$(!text,MEM):?words & :?output2:?output3 & whl

 ' ( !words:%?word %?words
   & !output2 rev$!word " ":?output2
   & " " !word !output3:?output3
   )

& str$(!output2 rev$!words):?output2 & str$(!words !output3):?output3 & out

 $ ( str
   $ ("0:\"" !text "\"\n1:\"" !output1 "\"\n2:\"" !output2 "\"\n3:\"" !output3 \"\n)
   )

);</lang> Output:

0:"rosetta code phrase reversal"
1:"lasrever esarhp edoc attesor"
2:"attesor edoc esarhp lasrever"
3:"reversal phrase code rosetta"

C

Working with C strings is often long-winded. <lang C>

  1. include <stdio.h>
  2. include <string.h>

/* The functions used are destructive, so after each call the string needs

* to be copied over again. One could easily allocate new strings as
* required, but this way allows the caller to manage memory themselves */

char* reverse_section(char *s, size_t length) {

   if (length == 0) return s;
   size_t i; char temp;
   for (i = 0; i < length / 2 + 1; ++i)
       temp = s[i], s[i] = s[length - i], s[length - i] = temp;
   return s;

}

char* reverse_words_in_order(char *s, char delim) {

   if (!strlen(s)) return s;
   size_t i, j;
   for (i = 0; i < strlen(s) - 1; ++i) {
       for (j = 0; s[i + j] != 0 && s[i + j] != delim; ++j)
           ;
       reverse_section(s + i, j - 1);
       s += j;
   }
   return s;

}

char* reverse_string(char *s) {

   return strlen(s) ? reverse_section(s, strlen(s) - 1) : s;

}

char* reverse_order_of_words(char *s, char delim) {

   reverse_string(s);
   reverse_words_in_order(s, delim);
   return s;

}

int main(void) {

   char str[]    = "rosetta code phrase reversal";
   size_t lenstr = sizeof(str) / sizeof(str[0]);
   char scopy[lenstr];
   char delim = ' ';
   /* Original String */
   printf("Original:       \"%s\"\n", str);
   /* Reversed string */
   strncpy(scopy, str, lenstr);
   reverse_string(scopy);
   printf("Reversed:       \"%s\"\n", scopy);
   /* Reversed words in string */
   strncpy(scopy, str, lenstr);
   reverse_words_in_order(scopy, delim);
   printf("Reversed words: \"%s\"\n", scopy);
   /* Reversed order of words in string */
   strncpy(scopy, str, lenstr);
   reverse_order_of_words(scopy, delim);
   printf("Reversed order: \"%s\"\n", scopy);
   return 0;

} </lang>

Output:
Original:       "rosetta code phrase reversal"
Reversed:       "lasrever esarhp edoc attesor"
Reversed words: "attesor edoc esarhp lasrever"
Reversed order: "reversal phrase code rosetta"

C++

<lang cpp>#include <iostream>

  1. include <iostream>
  2. include <vector>
  3. include <algorithm>
  4. include <string>
  5. include <iterator>
  6. include <sstream>

int main() {

  std::string s = "rosetta code phrase reversal";
  std::cout << "Input : " << s << '\n'
            << "Input reversed : " << std::string(s.rbegin(), s.rend()) << '\n' ;
  std::istringstream is(s);
  std::vector<std::string> words(std::istream_iterator<std::string>(is), {});
  std::cout << "Each word reversed : " ;
  for(auto w : words)
     std::cout << std::string(w.rbegin(), w.rend()) << ' ';
  std::cout << '\n'
            << "Original word order reversed : " ;
  reverse_copy(words.begin(), words.end(), std::ostream_iterator<std::string>(std::cout, " "));
  std::cout << '\n' ;

} </lang>

Output:
Input : rosetta code phrase reversal
Input reversed : lasrever esarhp edoc attesor
Each word reversed : attesor edoc esarhp lasrever 
Original word order reversed : reversal phrase code rosetta 

Clojure

<lang clojure>(use '[clojure.string :only (join split)]) (def phrase "rosetta code phrase reversal") (defn str-reverse [s] (apply str (reverse s)))

Reverse string

(str-reverse phrase)

Words reversed

(join " " (map str-reverse (split phrase #" ")))

Word order reversed

(apply str (interpose " " (reverse (split phrase #" ")))) </lang>

Output:
"lasrever esarhp edoc attesor"
"attesor edoc esarhp lasrever"
"reversal phrase code rosetta"

D

Partially lazy. <lang d>void main() @safe {

   import std.stdio, std.range, std.algorithm;
   immutable phrase = "rosetta code phrase reversal";
   phrase.retro.writeln;                          // Reversed string.
   phrase.splitter.map!retro.joiner(" ").writeln; // Words reversed.
   phrase.split.retro.joiner(" ").writeln;        // Word order reversed.

}</lang>

Output:
lasrever esarhp edoc attesor
attesor edoc esarhp lasrever
reversal phrase code rosetta

EchoLisp

<lang scheme> (define (string-reverse string)

   (list->string (reverse (string->list string))))

(define (task str)

   (for-each writeln (list
     (string-reverse str)
     (string-join (map string-reverse (string-split str )))
     (string-join (reverse (string-split str ))))))


(task "rosetta code phrase reversal")

   "lasrever esarhp edoc attesor"    
   "attesor edoc esarhp lasrever"    
   "reversal phrase code rosetta"    

</lang>

Elixir

<lang elixir>str = "rosetta code phrase reversal"

IO.puts String.reverse(str) IO.puts String.split(str) |> Enum.map(&String.reverse(&1)) |> Enum.join(" ") IO.puts String.split(str) |> Enum.reverse |> Enum.join(" ")</lang>

Output:
lasrever esarhp edoc attesor
attesor edoc esarhp lasrever
reversal phrase code rosetta

Emacs Lisp

<lang Emacs Lisp> (defun reverse-sep (words sep)

 (mapconcat 'identity (reverse (split-string words sep) ) sep) )

(defun reverse-chars (line)

 (reverse-sep line "") )

(defun reverse-words (line)

 (reverse-sep line " ") )

(progn

 (setq line "rosetta code phrase reversal")
 
 (insert (format "%s\n" (reverse-chars line) ))
 
   (insert (format "%s\n" 
       (mapconcat 'identity (mapcar #'reverse-chars 
                                    (split-string line) ) " ") ))
   
   (insert (format "%s\n" (reverse-words line) )))
</lang>

Output:

lasrever esarhp edoc attesor
attesor edoc esarhp lasrever
reversal phrase code rosetta                                                                                

Fortran

The key here is the ability via F90 to specify an array span, as A(first:last:step) where the step can be negative... This facility is not available for CHARACTER variables where only TEXT(first:last) is available - no step is accommodated. However, one can have an array of CHARACTER*1 variables, and as an array they can be rolled bidirectionally. For convenience in initialising such an array, EQUIVALENCE(TEXT,ATXT) means that a normal multi-character text literal can be assigned to TEXT via the DATA statement, rather than having to specify the ATXT elements one at a time.

By identifying the first and last character position of each word in TEXT (or equivalently, their indices in ATXT) and storing them in arrays IST and LST, the i'th word can be fingered via IST(i) to LST(i) and of course a DO-loop can step in either direction. <lang Fortran> PROGRAM REVERSER !Just fooling around.

     CHARACTER*(66) TEXT	!Holds the text. Easily long enough.
     CHARACTER*1 ATXT(66)	!But this is what I play with.
     EQUIVALENCE (TEXT,ATXT)	!Same storage, different access abilities..
     DATA TEXT/"Rosetta Code Phrase Reversal"/	!Easier to specify this for TEXT.
     INTEGER IST(6),LST(6)	!Start and stop positions.
     INTEGER N,L,I		!Counters.
     INTEGER L1,L2		!Fingers for the scan.
     CHARACTER*(*) AS,RW,FW,RO,FO			!Now for some cramming.
     PARAMETER (AS = "Words ordered as supplied")	!So that some statements can fit on a line.
     PARAMETER (RW = "Reversed words, ", FW = "Forward words, ")
     PARAMETER (RO = "reverse order",    FO = "forward order")

Chop the text into words.

     N = 0		!No words found.
     L = LEN(TEXT)	!Multiple trailing spaces - no worries.
     L2 = 0		!Syncopation: where the previous chomp ended.
  10 L1 = L2		!Thus, where a fresh scan should follow.
  11 L1 = L1 + 1		!Advance one.
     IF (L1.GT.L) GO TO 20		!Finished yet?
     IF (ATXT(L1).LE." ") GO TO 11	!No. Skip leading spaces.
     L2 = L1			!Righto, L1 is the first non-blank.
  12 L2 = L2 + 1		!Scan through the non-blanks.
     IF (L2.GT.L) GO TO 13	!Is it safe to look?
     IF (ATXT(L2).GT." ") GO TO 12	!Yes. Speed through non-blanks.
  13 N = N + 1			!Righto, a word is found in TEXT(L1:L2 - 1)
     IST(N) = L1		!So, recall its first character.
     LST(N) = L2 - 1		!And its last.
     IF (L2.LT.L) GO TO 10	!Perhaps more text follows.

Chuck the words around.

  20 WRITE (6,21) N,TEXT	!First, say what has been discovered.
  21 FORMAT (I4," words have been isolated from the text ",A,/)
     WRITE (6,22) AS,    (" ",ATXT(IST(I):LST(I):+1), I = 1,N,+1)
     WRITE (6,22) RW//RO,(" ",ATXT(LST(I):IST(I):-1), I = N,1,-1)
     WRITE (6,22) FW//RO,(" ",ATXT(IST(I):LST(I):+1), I = N,1,-1)
     WRITE (6,22) RW//FO,(" ",ATXT(LST(I):IST(I):-1), I = 1,N,+1)
  22 FORMAT (A36,":",66A1)
     END</lang>

With F77 such array spans can't be used, but all that is necessary is to supply a second implied DO-loop in the WRITE statement, for example <lang Fortran> WRITE (6,22) RW//RO,(" ",(ATXT(J), J = LST(I),IST(I),-1), I = 1,N,+1)</lang>

And the output is...

   4 words have been isolated from the text Rosetta Code Phrase Reversal

           Words ordered as supplied: Rosetta Code Phrase Reversal
       Reversed words, reverse order: lasreveR esarhP edoC attesoR
        Forward words, reverse order: Reversal Phrase Code Rosetta
       Reversed words, forward order: attesoR edoC esarhP lasreveR

Go

Simple

<lang go>package main

import ( "fmt" "strings" )

const phrase = "rosetta code phrase reversal"

func revStr(s string) string { rs := make([]rune, len(s)) i := len(s) for _, r := range s { i-- rs[i] = r } return string(rs[i:]) }

func main() { fmt.Println("Reversed: ", revStr(phrase))

ws := strings.Fields(phrase) for i, w := range ws { ws[i] = revStr(w) } fmt.Println("Words reversed: ", strings.Join(ws, " "))

ws = strings.Fields(phrase) last := len(ws) - 1 for i, w := range ws[:len(ws)/2] { ws[i], ws[last-i] = ws[last-i], w } fmt.Println("Word order reversed:", strings.Join(ws, " ")) }</lang>

Output:
Reversed:            lasrever esarhp edoc attesor
Words reversed:      attesor edoc esarhp lasrever
Word order reversed: reversal phrase code rosetta

Alternative

<lang go>package main

import ( "fmt" "regexp" "sort" "strings" )

const phrase = "rosetta code phrase reversal"

type reversible interface { Len() int Swap(i, j int) }

func reverse(p reversible) { mid := p.Len() / 2 last := p.Len() - 1 for i := 0; i < mid; i++ { p.Swap(i, last-i) } }

type runeSlice []rune

func (p runeSlice) Len() int { return len(p) } func (p runeSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }

func reverseString(s string) string { r := runeSlice(s) reverse(r) return string(r) }

var rx = regexp.MustCompile(`\S*`)

func reverseWords(s string) string { return rx.ReplaceAllStringFunc(s, func(m string) string { return reverseString(m) }) }

func reverseWordOrder(s string) string { l := sort.StringSlice(strings.Fields(s)) reverse(l) return strings.Join(l, " ") }

func main() { fmt.Println("Reversed: ", reverseString(phrase)) fmt.Println("Words reversed: ", reverseWords(phrase)) fmt.Println("Word order reversed:", reverseWordOrder(phrase)) }</lang>

Output:
Reversed:            lasrever esarhp edoc attesor
Words reversed:      attesor edoc esarhp lasrever
Word order reversed: reversal phrase code rosetta

Groovy

<lang groovy>def phaseReverse = { text, closure -> closure(text.split(/ /)).join(' ')}

def text = 'rosetta code phrase reversal' println "Original: $text" println "Reversed: ${phaseReverse(text) { it.reverse().collect { it.reverse() } } }" println "Reversed Words: ${phaseReverse(text) { it.collect { it.reverse() } } }" println "Reversed Order: ${phaseReverse(text) { it.reverse() } }"</lang>

Output:
Original:       rosetta code phrase reversal
Reversed:       lasrever esarhp edoc attesor
Reversed Words: attesor edoc esarhp lasrever
Reversed Order: reversal phrase code rosetta

Haskell

<lang haskell>phrase = "rosetta code phrase reversal"

main = do

 putStrLn $ reverse phrase
 putStrLn $ unwords . map reverse . words $ phrase
 putStrLn $ unwords . reverse . words $ phrase</lang>
Output:
lasrever esarhp edoc attesor
attesor edoc esarhp lasrever
reversal phrase code rosetta

J

Solution: <lang j> getWords=: (' '&splitstring) :. (' '&joinstring)

  reverseString=: |.
  reverseWords=: |.&.>&.getWords
  reverseWordOrder=: |.&.getWords</lang>

Usage: <lang j> phrase=: 'rosetta code phrase reversal'

  (reverseWordOrder , reverseWords ,: reverseString) phrase

reversal phrase code rosetta attesor edoc esarhp lasrever lasrever esarhp edoc attesor</lang>

Java

Works with: Java version 1.5+

<lang java5>import java.util.Arrays;

public class PhraseRev{ private static String reverse(String x){ return new StringBuilder(x).reverse().toString(); }

private static <T> T[] reverse(T[] x){ T[] rev = Arrays.copyOf(x, x.length); for(int i = x.length - 1; i >= 0; i--){ rev[x.length - 1 - i] = x[i]; } return rev; }

private static String join(String[] arr, String joinStr){ StringBuilder joined = new StringBuilder(); for(int i = 0; i < arr.length; i++){ joined.append(arr[i]); if(i < arr.length - 1) joined.append(joinStr); } return joined.toString(); }

public static void main(String[] args){ String str = "rosetta code phrase reversal";

System.out.println("Straight-up reversed: " + reverse(str)); String[] words = str.split(" "); for(int i = 0; i < words.length; i++){ words[i] = reverse(words[i]); } System.out.println("Reversed words: " + join(words, " ")); System.out.println("Reversed word order: " + join(reverse(str.split(" ")), " ")); } }</lang>

Output:
Straight-up reversed: lasrever esarhp edoc attesor
Reversed words: attesor edoc esarhp lasrever
Reversed word order: reversal phrase code rosetta

JavaScript

<lang JavaScript>(function (p) {

 return [
   p.split().reverse().join(),
   p.split(' ').map(function (x) {
       return x.split().reverse().join();
   }).join(' '),
   p.split(' ').reverse().join(' ')
 ].join('\n');

})('rosetta code phrase reversal');</lang>

Output:
lasrever esarhp edoc attesor
attesor edoc esarhp lasrever
reversal phrase code rosetta

jq

Works with: jq version 1.4

<lang jq>def reverse_string: explode | reverse | implode;

"rosetta code phrase reversal" | split(" ") as $words | "0. input: \(.)",

 "1. string reversed:     \(reverse_string)",
 "2. each word reversed:  \($words | map(reverse_string) | join(" "))",
 "3. word-order reversed: \($words | reverse | join(" "))"</lang>
Output:
$ jq -r -n -f Phrase_reversals.jq
0. input:               rosetta code phrase reversal
1. string reversed:     lasrever esarhp edoc attesor
2. each word reversed:  attesor edoc esarhp lasrever
3. word-order reversed: reversal phrase code rosetta

Julia

<lang Julia> s = "rosetta code phrase reversal"

println("The original phrase.") println(" ", s)

println("Reverse the string.") t = reverse(s) println(" ", t)

println("Reverse each individual word in the string.") t = join(map(reverse, split(s, " ")), " ") println(" ", t)

println("Reverse the order of each word of the phrase.") t = join(reverse(split(s, " ")), " ") println(" ", t) </lang>

Output:
The original phrase.
   rosetta code phrase reversal
Reverse the string.
   lasrever esarhp edoc attesor
Reverse each individual word in the string.
   attesor edoc esarhp lasrever
Reverse the order of each word of the phrase.
   reversal phrase code rosetta

Lua

<lang Lua>-- Return a copy of table t in which each string is reversed function reverseEach (t)

   local rev = {}
   for k, v in pairs(t) do rev[k] = v:reverse() end
   return rev

end

-- Return a reversed copy of table t function tabReverse (t)

   local revTab = {}
   for i, v in ipairs(t) do revTab[#t - i + 1] = v end
   return revTab

end

-- Split string str into a table on space characters function wordSplit (str)

   local t = {}
   for word in str:gmatch("%S+") do table.insert(t, word) end
   return t

end

-- Main procedure local str = "rosetta code phrase reversal" local tab = wordSplit(str) print("1. " .. str:reverse()) print("2. " .. table.concat(reverseEach(tab), " ")) print("3. " .. table.concat(tabReverse(tab), " "))</lang>

Output:
1. lasrever esarhp edoc attesor
2. attesor edoc esarhp lasrever
3. reversal phrase code rosetta

Mathematica / Wolfram Language

<lang Mathematica>phrase = "Rosetta Code Phrase Reversal";

reverseWords[phrase_String] :=

StringJoin @@ Riffle[Reverse@StringSplit@phrase, " "]

reverseLetters[phrase_String] :=

StringJoin @@ 
 Riffle[Map[StringJoin @@ Reverse[Characters@#] &, 
   StringSplit@phrase], " "]

{phrase, reverseWords@phrase, reverseLetters@phrase,

 reverseWords@reverseLetters@phrase} // TableForm</lang>
Output:

Rosetta Code Phrase Reversal Reversal Phrase Code Rosetta attesoR edoC esarhP lasreveR lasreveR esarhP edoC attesoR

Oforth

<lang Oforth>"rosetta code phrase reversal" reverse println "rosetta code phrase reversal" words map(#reverse) reduce(#[ " " swap + + ]) println "rosetta code phrase reversal" words reverse reduce(#[ " " swap + + ]) println</lang>

Output:
lasrever esarhp edoc attesor
attesor edoc esarhp lasrever
reversal phrase code rosetta

Perl

<lang perl>use feature 'say'; my $s = "rosetta code phrase reversal";

say "0. Input  : ", $s; say "1. String reversed  : ", scalar reverse $s; say "2. Each word reversed  : ", join " ", reverse split / /, reverse $s; say "3. Word-order reversed : ", join " ", reverse split / /,$s;

  1. Or, using a regex:

say "2. Each word reversed  : ", $s =~ s/[^ ]+/reverse $&/gre;</lang>

Output:
0. Input               : rosetta code phrase reversal
1. String reversed     : lasrever esarhp edoc attesor
2. Each word reversed  : attesor edoc esarhp lasrever
3. Word-order reversed : reversal phrase code rosetta
2. Each word reversed  : attesor edoc esarhp lasrever

Perl 6

<lang perl6>my $s = 'rosetta code phrase reversal';

say 'Input  : ', $s; say 'String reversed  : ', $s.flip; say 'Each word reversed  : ', $s.words».flip; say 'Word-order reversed : ', $s.words.reverse;</lang>

Output:
Input               : rosetta code phrase reversal
String reversed     : lasrever esarhp edoc attesor
Each word reversed  : attesor edoc esarhp lasrever
Word-order reversed : reversal phrase code rosetta

PHP

<lang php><?php // Initialize a variable with the input desired $strin = "rosetta code phrase reversal";

// Show user what original input was echo "Input: ".$strin."\n";

// Show the full input reversed echo "Reversed: ".strrev($strin)."\n";

// reverse the word letters in place $str_words_reversed = ""; $temp = explode(" ", $strin); foreach($temp as $word) $str_words_reversed .= strrev($word)." ";

// Show the reversed words in place echo "Words reversed: ".$str_words_reversed."\n";


// reverse the word order while leaving the words in order $str_word_order_reversed = ""; $temp = explode(" ", $strin); for($i=(count($temp)-1); $i>=0; $i--) $str_word_order_reversed .= $temp[$i]." ";

// Show the reversal of the word order while leaving the words in order echo "Word order reversed: ".$str_word_order_reversed."\n"; </lang>

Input: rosetta code phrase reversal
Reversed: lasrever esarhp edoc attesor
Words reversed: attesor edoc esarhp lasrever 
Word order reversed: reversal phrase code rosetta

PL/I

<lang PL/I> reverser: procedure options (main); /* 19 August 2015 */

  declare (phrase, r, word) character (100) varying;
  declare (start, end) fixed binary;
  phrase = 'rosetta code phrase reversal';
  put ('The original phrase is: ' || phrase);
  put skip list ( '1. ' || reverse(phrase) );
  start = 1; r = ; put skip edit ('2. ') (a);
  do until ( end > length(phrase) );
     end = index(phrase, ' ', start);          /* Find end of the next word.*/
     if end = 0 then end = length(phrase) + 1; /* We're at the last word.   */
     word = substr(phrase, start, end-start);
     put edit ( reverse(word), ' ' ) (a);      /* Append reversed word.     */
     r = word || ' ' || r;                     /* Prepend normal word.      */
     start = end+1;
  end;
  put skip list ('3. ' || r);

end reverser; </lang> Output:

The original phrase is: rosetta code phrase reversal 
1. lasrever esarhp edoc attesor 
2. attesor edoc esarhp lasrever 
3. reversal phrase code rosetta  

PowerShell

<lang PowerShell> function reverse($a, $sep = "") {

   if($a.Length -gt 0) {
       $a = $a[($a.Length -1)..0] -join $sep
   }
   $a

} $line = "rosetta code phrase reversal" $task1 = reverse $line $task2 = ($line -split " " | foreach{ reverse $_ }) -join " " $task3 = reverse ($line -split " ") " " $task1 $task2 $task3

</lang>

Output:

lasrever esarhp edoc attesor
attesor edoc esarhp lasrever
reversal phrase code rosetta                                                                             

Python

These examples use the extended slicing notation of [::-1] to reverse strings and lists of strings: <lang python>>>> phrase = "rosetta code phrase reversal" >>> phrase[::-1] # Reversed. 'lasrever esarhp edoc attesor' >>> ' '.join(word[::-1] for word in phrase.split()) # Words reversed. 'attesor edoc esarhp lasrever' >>> ' '.join(word for word in phrase.split()[::-1]) # Word order reversed. 'reversal phrase code rosetta' >>> </lang>

Racket

<lang racket>#lang racket/base (require

 (only-in srfi/13 string-reverse)
 (only-in racket/string string-split string-join))

(define (phrase-reversal s)

 (list
  (string-reverse s)
  (string-join (map string-reverse (string-split s)))
  (string-join (reverse (string-split s)))))

(for-each displayln (phrase-reversal "rosetta code phrase reversal"))</lang>

Output:
lasrever esarhp edoc attesor
attesor edoc esarhp lasrever
reversal phrase code rosetta

REXX

version 1

Working with REXX (strings and words) is trivial. <lang rexx>s='rosetta code phrase reversal' r1=reverse(s) r2= Do i=1 To words(s)

 r2=r2 reverse(word(s,i))
 End

r2=strip(r2) r3= Do i=words(s) To 1 By -1

 r3=r3 word(s,i)
 End

r3=strip(r3) Say "input  : " s say "string reversed  : " r1 say "each word reversed  : " r2 say "word-order reversed : " r3</lang>

Output:
input               :  rosetta code phrase reversal
string reversed     :  lasrever esarhp edoc attesor
each word reversed  :  attesor edoc esarhp lasrever
word-order reversed :  reversal phrase code rosetta

version 2

<lang rexx>/*REXX pgm reverses words and/or letters in a string in various ways. */ i=; p=; parse arg $; if $= then $="rosetta code phrase reversal"

                                      do j=1  for words($);   _=word($,j)
                                      i=i reverse(_)      ;   p=_ p
                                      end   /*j*/

say ' the original phrase used: ' $ say ' original phrase reversed: ' reverse($) say 'reversed individual words: ' strip(i) say 'reversed words in phrases: ' p /*stick a fork in it, we're done.*/</lang> output when using the default string:

 the original phrase used:  rosetta code phrase reversal
 original phrase reversed:  lasrever esarhp edoc attesor
reversed individual words:  attesor edoc esarhp lasrever
reversed words in phrases:  reversal phrase code rosetta

Ring

This example is incorrect. Please fix the code and remove this message.

Details: No output, wrong example string, ...

<lang ring> aString = "Welcome to the Ring Language" bString = "" see reverseString(aString)

func reverseString cString

    for i= len(cString) to 1 step -1
        bString = bString + cString[i]
    next
    return bString

</lang>

Ruby

<lang ruby>str = "rosetta code phrase reversal"

puts str.reverse # Reversed string. puts str.split.map(&:reverse).join(" ") # Words reversed. puts str.split.reverse.join(" ") # Word order reversed.</lang>

Output:
lasrever esarhp edoc attesor
attesor edoc esarhp lasrever
reversal phrase code rosetta

Sidef

<lang ruby>var str = "rosetta code phrase reversal";

say str.reverse; # reversed string say str.words.map{.reverse}.join(' '); # words reversed say str.words.reverse.join(' '); # word order reversed</lang>

Output:
lasrever esarhp edoc attesor
attesor edoc esarhp lasrever
reversal phrase code rosetta

Tcl

<lang tcl>set s "rosetta code phrase reversal"

  1. Reverse all characters

puts [string reverse $s]

  1. Reverse characters in each word

puts [lmap word $s {string reverse $word}]

  1. Reverse the words but not the characters

puts [lreverse $s]</lang>

Output:
lasrever esarhp edoc attesor
attesor edoc esarhp lasrever
reversal phrase code rosetta

UNIX Shell

Version 1

Requires "rev" command.

Works with: Almquist Shell
Works with: bash
Works with: ksh93

<lang sh>s1="rosetta code phrase reversal" echo "Original string ----------------------> "$s1

echo -n "1.) Reverse the string ---------------> " echo $s1|rev

echo -n "2.) Reverse characters of each word --> " echo $s1|tr " " "\n"|rev|tr "\n" " ";echo

echo -n "3.) Reverse word order ---------------> " word_num=$(echo $s1|wc -w) while [ $word_num != 0 ];do echo -n $(echo $s1|cut -d " " -f $word_num);echo -n " " word_num=$(expr $word_num - 1);done;echo</lang>

Output:
Original string ----------------------> rosetta code phrase reversal
1.) Reverse the string ---------------> lasrever esarhp edoc attesor
2.) Reverse characters of each word --> attesor edoc esarhp lasrever
3.) Reverse word order ---------------> reversal phrase code rosetta

Version 2

Does not require "rev" command.

Works with: Almquist Shell
Works with: bash
Works with: ksh93

<lang sh>s1="rosetta code phrase reversal" echo "Original string --> "$s1

echo -n "1.) Reverse the string --> " length=$(echo $s1|wc -c) while [ $length != 0 ];do echo $s1|cut -c$length|tr -d "\n" length=$(expr $length - 1) done;echo

echo -n "2.) Reverse characters of each word --> " word_quantity=$(echo $s1|wc -w) word_quantity=$(expr $word_quantity + 1) word_num=1 while [ $word_num != $word_quantity ];do length=$(echo $s1|cut -d " " -f $word_num|wc -c) while [ $length != 0 ];do echo $s1|cut -d " " -f $word_num|cut -c$length|tr -d "\n" length=$(expr $length - 1);done;echo -n " " word_num=$(expr $word_num + 1);done;echo

echo -n "3.) Reverse word order --> " word_num=$(echo $s1|wc -w) while [ $word_num != 0 ];do echo -n $(echo $s1|cut -d " " -f $word_num);echo -n " " word_num=$(expr $word_num - 1);done;echo</lang>

Output:
Original string                     --> rosetta code phrase reversal
1.) Reverse the string              --> lasrever esarhp edoc attesor
2.) Reverse characters of each word --> attesor edoc esarhp lasrever
3.) Reverse word order              --> reversal phrase code rosetta

VBScript

<lang vb> Phrase = "rosetta code phrase reversal"

WScript.StdOut.Write "Original String  : " & Phrase WScript.StdOut.WriteLine WScript.StdOut.Write "Reverse String  : " & RevString(Phrase) WScript.StdOut.WriteLine WScript.StdOut.Write "Reverse String Each Word : " & RevStringEachWord(Phrase) WScript.StdOut.WriteLine WScript.StdOut.Write "Reverse Phrase  : " & RevPhrase(Phrase) WScript.StdOut.WriteLine

Function RevString(s) x = Len(s) For i = 1 To Len(s) RevString = RevString & Mid(s,x,1) x = x - 1 Next End Function

Function RevStringEachWord(s) arr = Split(s," ") For i = 0 To UBound(arr) RevStringEachWord = RevStringEachWord & RevString(arr(i)) If i < UBound(arr) Then RevStringEachWord = RevStringEachWord & " " End If Next End Function

Function RevPhrase(s) arr = Split(s," ") For i = UBound(arr) To LBound(arr) Step -1 RevPhrase = RevPhrase & arr(i) If i > LBound(arr) Then RevPhrase = RevPhrase & " " End If Next End Function </lang>

Output:
Original String          : rosetta code phrase reversal
Reverse String           : lasrever esarhp edoc attesor
Reverse String Each Word : attesor edoc esarhp lasrever
Reverse Phrase           : reversal phrase code rosetta

zkl

<lang zkl>zkl: var str="rosetta code phrase reversal" rosetta code phrase reversal

zkl: str.reverse() #1 lasrever esarhp edoc attesor

zkl: str.split().apply("reverse").concat(" ") #2 string to list to string attesor edoc esarhp lasrever

zkl: str.split().reverse().concat(" ") #3 reversal phrase code rosetta</lang>