Phrase reversals: Difference between revisions

Add Refal
(Rename Perl 6 -> Raku, alphabetize, minor clean-up)
(Add Refal)
 
(34 intermediate revisions by 29 users not shown)
Line 12:
 
{{Template:Strings}}
;See also:
* [[Reverse a string]]
* [[Reverse words in a string]]
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V phrase = ‘rosetta code phrase reversal’
print(reversed(phrase))
print(phrase.split(‘ ’).map(word -> reversed(word)).join(‘ ’))
print(reversed(phrase.split(‘ ’)).join(‘ ’))</syntaxhighlight>
 
{{out}}
<pre>
lasrever esarhp edoc attesor
attesor edoc esarhp lasrever
reversal phrase code rosetta
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC ReversePart(CHAR ARRAY src,dst BYTE start,len)
BYTE i
 
FOR i=0 TO len-1
DO
dst(start+len-i-1)=src(start+i)
OD
RETURN
 
PROC ReverseString(CHAR ARRAY src,dst)
BYTE i
 
dst(0)=src(0)
ReversePart(src,dst,1,src(0))
RETURN
 
PROC ReverseInWords(CHAR ARRAY src,dst)
BYTE i,start
 
dst(0)=src(0)
i=1
WHILE i<=src(0)
DO
IF src(i)=32 THEN
dst(i)=32 i==+1
ELSE
start=i
WHILE i<=src(0) AND src(i)#32
DO i==+1 OD
ReversePart(src,dst,start,i-start)
FI
OD
RETURN
 
PROC ReverseWords(CHAR ARRAY src,dst)
CHAR ARRAY tmp(100)
ReverseString(src,tmp)
ReverseInWords(tmp,dst)
RETURN
 
PROC Main()
CHAR ARRAY s="rosetta code phrase reversal",rev(100)
 
PrintE(s)
ReverseString(s,rev)
PrintE(rev)
ReverseInWords(s,rev)
PrintE(rev)
ReverseWords(s,rev)
PrintE(rev)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Phrase_reversals.png Screenshot from Atari 8-bit computer]
<pre>
rosetta code phrase reversal
lasrever esarhp edoc attesor
attesor edoc esarhp lasrever
reversal phrase code rosetta
</pre>
 
=={{header|Ada}}==
Line 22 ⟶ 97:
[[http://rosettacode.org/wiki/Reverse_words_in_a_string#Ada]] is used.
 
<langsyntaxhighlight Adalang="ada"><with Ada.Text_IO, Simple_Parse;
 
procedure Phrase_Reversal is
Line 64 ⟶ 139:
Put_Line("2. Reverse words, same order: """ & Reverse_Words(Phrase) & """");
Put_Line("2. Reverse order, same words: """ & Reverse_Order(Phrase) & """");
end Phrase_Reversal;</langsyntaxhighlight>
 
{{out}}
Line 75 ⟶ 150:
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<langsyntaxhighlight 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
Line 129 ⟶ 204:
, original phrase, ": order reversed -> ", order reversed, newline
)
)</langsyntaxhighlight>
{{out}}
<pre>
Line 139 ⟶ 214:
 
=={{header|AppleScript}}==
===Functional===
 
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.
Line 144 ⟶ 220:
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).
 
<langsyntaxhighlight AppleScriptlang="applescript">-- REVERSED PHRASES, COMPONENT WORDS, AND WORD ORDER ---------------------
 
-- reverseString, reverseEachWord, reverseWordOrder :: String -> String
Line 267 ⟶ 343:
on unwords(lstWords)
intercalate(space, lstWords)
end unwords</langsyntaxhighlight>
{{out}}
<pre>"lasrever esarhp edoc attesor
Line 273 ⟶ 349:
reversal phrase code rosetta"</pre>
 
----
===Idiomatic===
 
<syntaxhighlight lang="applescript">set aString to "rosetta code phrase reversal"
Alternatively:
 
<lang applescript>set aString to "rosetta code phase reversal"
 
set astid to AppleScript's text item delimiters
 
set AppleScript's text item delimiters to ""
set phase1phrase1 to (reverse of characters of aString) as text
 
set AppleScript's text item delimiters to space
set phase2phrase2 to (reverse of words of phase1phrase1) as text
 
set phase3 to (reverse of words of aString) as text
set phrase3 to (reverse of words of aString) as text
 
set AppleScript's text item delimiters to linefeed
set output to {phase1phrase1, phase2phrase2, phase3phrase3} as text
 
set AppleScript's text item delimiters to astid
 
return output</langsyntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">"lasrever esarhp edoc attesor
attesor edoc esarhp lasrever
reversal phrase code rosetta"</syntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">phr: "rosetta code phrase reversal"
 
print ["(0)" phr]
print ["(1)" reverse phr]
print ["(2)" join.with:" " map split.words phr => reverse]
print ["(3)" join.with:" " reverse split.words phr]</syntaxhighlight>
 
{{out}}
 
<pre>"lasrever esahp edoc attesor
<pre>(0) rosetta code phrase reversal
attesor edoc esahp lasrever
(1) lasrever esarhp edoc attesor
reversal phase code rosetta"</pre>
(2) attesor edoc esarhp lasrever
(3) reversal phrase code rosetta</pre>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">var =
<lang AutoHotKey>var =
(
Rosetta Code Phrase Reversal
Line 329 ⟶ 426:
ExitApp
 
esc::ExitApp</langsyntaxhighlight>
 
{{out}}
Line 340 ⟶ 437:
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk"># Usage: awk -f phrase_revers.awk
function rev(s, del, n,i,a,r) {
n = split(s, a, del)
Line 357 ⟶ 454:
printf( fmt, "word-order reversed", wr )
printf( fmt, "each word reversed", rev(wr) )
}</langsyntaxhighlight>
{{Out}}
<pre>
Line 366 ⟶ 463:
</pre>
 
=={{header|BaConBASIC}}==
==={{header|Applesoft BASIC}}===
<lang qbasic>phrase$ = "rosetta code phrase reversal"
<syntaxhighlight lang="basic"> 10 PHRA$ = "rosetta code phrase reversal"
20 GOSUB 100
30 PRINT PHRA$(0)
40 PRINT PHRA$(1)
50 PRINT PHRA$(2);
60 END
100 FOR PH = 0 TO 6
110 PH$(PH) = ""
120 NEXT PH
130 FOR PH = 0 TO LEN (PH$)
140 PH$(4) = MID$ (PH$,PH + (PH < 255),PH < 255)
150 PH$(0) = PH$(4) + PH$(0)
160 IF PH$(4) = " " THEN GOSUB 200
170 PH$(5) = PH$(5) + PH$(4)
180 PH$(6) = PH$(4) + PH$(6)
190 NEXT PH
200 PH$(1) = PH$(1) + PH$(3) + PH$(6)
210 PH$(2) = PH$(5) + PH$(3) + PH$(2)
220 PH$(3) = " "
230 PH$(4) = ""
240 PH$(5) = ""
250 PH$(6) = ""
260 RETURN</syntaxhighlight>{{out}}
<pre>
lasrever esarhp edoc attesor
attesor edoc esarhp lasrever
reversal phrase code rosetta</pre>
 
==={{header|BaCon}}===
<syntaxhighlight lang="basic">phrase$ = "rosetta code phrase reversal"
 
PRINT REVERSE$(phrase$)
Line 373 ⟶ 500:
PRINT REV$(REVERSE$(phrase$))
 
PRINT REV$(phrase$)</langsyntaxhighlight>
{{out}}
<pre>
Line 379 ⟶ 506:
attesor edoc esarhp lasrever
reversal phrase code rosetta
</pre>
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Sub split (s As Const String, sepList As Const String, result() As String)
If s = "" OrElse sepList = "" Then
Redim result(0)
result(0) = s
Return
End If
Dim As Integer i, j, count = 0, empty = 0, length
Dim As Integer position(Len(s) + 1)
position(0) = 0
For i = 0 To len(s) - 1
For j = 0 to Len(sepList) - 1
If s[i] = sepList[j] Then
count += 1
position(count) = i + 1
End If
Next j
Next i
Redim result(count)
If count = 0 Then
result(0) = s
Return
End If
position(count + 1) = len(s) + 1
For i = 1 To count + 1
length = position(i) - position(i - 1) - 1
result(i - 1) = Mid(s, position(i - 1) + 1, length)
Next
End Sub
 
Function reverse(s As Const String) As String
If s = "" Then Return ""
Dim t As String = s
Dim length As Integer = Len(t)
For i As Integer = 0 to length\2 - 1
Swap t[i], t[length - 1 - i]
Next
Return t
End Function
 
Dim s As String = "rosetta code phrase reversal"
Dim a() As String
Dim sepList As String = " "
 
Print "Original string => "; s
Print "Reversed string => "; reverse(s)
Print "Reversed words => ";
split s, sepList, a()
For i As Integer = LBound(a) To UBound(a)
Print reverse(a(i)); " ";
Next
Print
Print "Reversed order => ";
For i As Integer = UBound(a) To LBound(a) Step -1
Print a(i); " ";
Next
Print : Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
 
{{out}}
<pre>
Original string => rosetta code phrase reversal
Reversed string => lasrever esarhp edoc attesor
Reversed words => attesor edoc esarhp lasrever
Reversed order => reversal phrase code rosetta
</pre>
 
==={{header|Gambas}}===
'''[https://gambas-playground.proko.eu/?gist=77cb8b3386a0f57524bdbff6634387cd Click this link to run this code]'''
<syntaxhighlight lang="gambas">
Public Sub Main()
Dim sString As String = "rosetta code phrase reversal" 'The string
Dim sNewString, sTemp As String 'String variables
Dim siCount As Short 'Counter
Dim sWord As New String[] 'Word store
 
For siCount = Len(sString) DownTo 1 'Loop backwards through the string
sNewString &= Mid(sString, sicount, 1) 'Add each character to the new string
Next
 
Print "Original string = \t" & sString & "\n" & 'Print the original string
"Reversed string = \t" & sNewString 'Print the reversed string
 
sNewString = "" 'Reset sNewString
 
For Each sTemp In Split(sString, " ") 'Split the original string by the spaces
sWord.Add(sTemp) 'Add each word to sWord array
Next
 
For siCount = sWord.max DownTo 0 'Loop backward through each word in sWord
sNewString &= sWord[siCount] & " " 'Add each word to to sNewString
Next
 
Print "Reversed word order = \t" & sNewString 'Print reversed word order
 
sNewString = "" 'Reset sNewString
For Each sTemp In sWord 'For each word in sWord
For siCount = Len(sTemp) DownTo 1 'Loop backward through the word
sNewString &= Mid(sTemp, siCount, 1) 'Add the characters to sNewString
Next
sNewString &= " " 'Add a space at the end of each word
Next
 
Print "Words reversed = \t" & sNewString 'Print words reversed
 
End</syntaxhighlight>
Output:
<pre>
Original string = rosetta code phrase reversal
Reversed string = lasrever esarhp edoc attesor
Reversed word order = reversal phrase code rosetta
Words reversed = attesor edoc esarhp lasrever
</pre>
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang="basic">
100 PROGRAM "ReverseS.bas"
110 LET S$="Rosetta Code Pharse Reversal"
120 PRINT S$
130 PRINT REVERSE$(S$)
140 PRINT REVERSEW$(S$)
150 PRINT REVERSEC$(S$)
160 DEF REVERSE$(S$)
170 LET T$=""
180 FOR I=LEN(S$) TO 1 STEP-1
190 LET T$=T$&S$(I)
200 NEXT
210 LET REVERSE$=T$
220 END DEF
230 DEF REVERSEW$(S$)
240 LET T$="":LET PE=LEN(S$)
250 FOR PS=PE TO 1 STEP-1
260 IF PS=1 OR S$(PS)=" " THEN LET T$=T$&" ":LET T$=T$&LTRIM$(S$(PS:PE)):LET PE=PS-1
270 NEXT
280 LET REVERSEW$=LTRIM$(T$)
290 END DEF
300 DEF REVERSEC$(S$)
310 LET T$="":LET PS=1
320 FOR PE=1 TO LEN(S$)
330 IF PE=LEN(S$) OR S$(PE)=" " THEN LET T$=T$&" ":LET T$=T$&REVERSE$(RTRIM$(S$(PS:PE))):LET PS=PE+1
340 NEXT
350 LET REVERSEC$=LTRIM$(T$)
360 END DEF</syntaxhighlight>
 
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">
#TEXT="rosetta code phrase reversal"
 
If OpenConsole("rosetta code phrase reversal")
Define idx.i=1, txt.s=""
Print(~"Original:\t\t")
PrintN(#TEXT)
Print(~"Reversed:\t\t")
PrintN(ReverseString(#TEXT))
Print(~"Reversed words:\t\t")
txt=StringField(#TEXT,idx," ")
While Len(txt)
Print(ReverseString(txt)+" ")
idx+1
txt=StringField(#TEXT,idx," ")
Wend
PrintN("")
Print(~"Reversed order:\t\t")
idx-1
txt=StringField(#TEXT,idx," ")
While Len(txt)
Print(txt+" ")
If idx>1 : idx-1 : Else : Break : EndIf
txt=StringField(#TEXT,idx," ")
Wend
Input()
EndIf</syntaxhighlight>
{{out}}
<pre>Original: rosetta code phrase reversal
Reversed: lasrever esarhp edoc attesor
Reversed words: attesor edoc esarhp lasrever
Reversed order: reversal phrase code rosetta
</pre>
 
==={{header|VBA}}===
<syntaxhighlight lang="vbnet">
Option Explicit
 
Sub Main_Phrase_Reversals()
Const PHRASE As String = "rosetta code phrase reversal"
Debug.Print "Original String : " & PHRASE
Debug.Print "Reverse String : " & Reverse_String(PHRASE)
Debug.Print "Reverse each individual word : " & Reverse_each_individual_word(PHRASE)
Debug.Print "Reverse order of each word : " & Reverse_the_order_of_each_word(PHRASE)
End Sub
 
Function Reverse_String(strPhrase As String) As String
Reverse_String = StrReverse(strPhrase)
End Function
 
Function Reverse_each_individual_word(strPhrase As String) As String
Dim Words, i&, strTemp$
Words = Split(strPhrase, " ")
For i = 0 To UBound(Words)
Words(i) = Reverse_String(CStr(Words(i)))
Next i
Reverse_each_individual_word = Join(Words, " ")
End Function
 
Function Reverse_the_order_of_each_word(strPhrase As String) As String
Dim Words, i&, strTemp$
 
Words = Split(strPhrase, " ")
For i = UBound(Words) To 0 Step -1
strTemp = strTemp & " " & Words(i)
Next i
Reverse_the_order_of_each_word = Trim(strTemp)
End Function
</syntaxhighlight>
{{out}}
<pre>Original String : rosetta code phrase reversal
Reverse String : lasrever esarhp edoc attesor
Reverse each individual word : attesor edoc esarhp lasrever
Reverse order of each word : reversal phrase code rosetta</pre>
 
==={{header|VBScript}}===
<syntaxhighlight lang="vbscript">
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
</syntaxhighlight>
{{Out}}
<pre>
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
</pre>
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
%=== The Main Thing... ===%
Line 430 ⟶ 838:
set %var3%=!%var3%:~1,1000000!
goto :EOF
%=== /Reverse each Words Function ===%</langsyntaxhighlight>
{{Out}}
<pre>Original: Rosetta Code phrase reversal
Line 439 ⟶ 847:
=={{header|Bracmat}}==
This example only works correctly with strings only consisting of byte-sized characters.
<langsyntaxhighlight lang="bracmat">( "rosetta code phrase reversal":?text
& rev$!text:?output1
& get$(!text,MEM):?words
Line 454 ⟶ 862:
$ ("0:\"" !text "\"\n1:\"" !output1 "\"\n2:\"" !output2 "\"\n3:\"" !output3 \"\n)
)
);</langsyntaxhighlight>
Output:
<pre>0:"rosetta code phrase reversal"
Line 463 ⟶ 871:
=={{header|C}}==
Working with C strings is often long-winded.
<syntaxhighlight lang="c">
<lang C>
#include <stdio.h>
#include <string.h>
Line 534 ⟶ 942:
return 0;
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 545 ⟶ 953:
=={{header|C sharp}}==
 
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
namespace ConsoleApplication
Line 566 ⟶ 974:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <iostream>
#include <vector>
#include <algorithm>
Line 590 ⟶ 997:
reverse_copy(words.begin(), words.end(), std::ostream_iterator<std::string>(std::cout, " "));
std::cout << '\n' ;
}</syntaxhighlight>
}
</lang>
{{Out}}
<pre>Input : rosetta code phrase reversal
Line 600 ⟶ 1,006:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(use '[clojure.string :only (join split)])
(def phrase "rosetta code phrase reversal")
(defn str-reverse [s] (apply str (reverse s)))
Line 610 ⟶ 1,016:
; Word order reversed
(apply str (interpose " " (reverse (split phrase #" "))))
</syntaxhighlight>
</lang>
{{out}}
<pre>"lasrever esarhp edoc attesor"
Line 617 ⟶ 1,023:
 
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
<lang COBOL>
program-id. phra-rev.
data division.
Line 653 ⟶ 1,059:
.
end program phra-rev.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 663 ⟶ 1,069:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">
(defun split-string (str)
"Split a string into space separated words including spaces"
Line 681 ⟶ 1,087:
nil )
 
</syntaxhighlight>
</lang>
{{out}}<pre>(task "rosetta code phrase reversal")
 
Line 692 ⟶ 1,098:
=={{header|D}}==
Partially lazy.
<langsyntaxhighlight lang="d">void main() @safe {
import std.stdio, std.range, std.algorithm;
 
Line 699 ⟶ 1,105:
phrase.splitter.map!retro.joiner(" ").writeln; // Words reversed.
phrase.split.retro.joiner(" ").writeln; // Word order reversed.
}</langsyntaxhighlight>
{{out}}
<pre>lasrever esarhp edoc attesor
attesor edoc esarhp lasrever
reversal phrase code rosetta</pre>
 
=={{header|dt}}==
<syntaxhighlight lang="dt">"rosetta code phrase reversal" dup
rev pl
words dup
\rev map unwords pl
rev unwords pl</syntaxhighlight>
{{out}}
<pre>lasrever esarhp edoc attesor
attesor edoc esarhp lasrever
reversal phrase code rosetta</pre>
 
=={{header|Dyalect}}==
<syntaxhighlight lang="dyalect">let str = "rosetta code phrase reversal"
//or you can use a built-in method String.reverse
func reverse(str) {
let xs = []
for i in (str.Length()-1)^-1..0 {
xs.Add(str[i])
}
String.Concat(values: xs)
}
func reverseByWord(str) {
let words = str.Split(" ")
let xs = []
for w in words {
xs.Add(reverse(w))
xs.Add(" ")
}
String.Concat(values: xs)
}
func reverseWords(str) {
let words = str.Split(" ")
let xs = []
for i in (words.Length()-1)^-1..0 {
xs.Add(words[i])
xs.Add(" ")
}
String.Concat(values: xs)
}
print("1. \(reverse(str))")
print("2. \(reverseByWord(str))")
print("3. \(reverseWords(str))")</syntaxhighlight>
 
{{out}}
 
<pre>1. lasrever esarhp edoc attesor
2. attesor edoc esarhp lasrever
3. reversal phrase code rosetta </pre>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(define (string-reverse string)
(list->string (reverse (string->list string))))
Line 721 ⟶ 1,180:
"attesor edoc esarhp lasrever"
"reversal phrase code rosetta"
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
ELENA 46.x :
<langsyntaxhighlight lang="elena">import extensions;
import extensions'text;
import system'routines;
Line 739 ⟶ 1,198:
console.printLine(reverse(phrase));
//Reverse each individual word in the string, maintaining original string order.
console.printLine(phrase.splitBy:(" ").selectBy::(s => reverse(s).add(" ")).summarize(new StringWriter()));
//Reverse the order of each word of the phrase, maintaining the order of characters in each word.
console.printLine(reverse(phrase.splitBy:(" ").selectBy::(s => s + " ")))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 752 ⟶ 1,211:
 
=={{header|Elixir}}==
<langsyntaxhighlight 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(" ")</langsyntaxhighlight>
 
{{out}}
Line 766 ⟶ 1,225:
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(defun reverse-sep (words sep)
<lang Emacs Lisp>
(defunmapconcat 'identity (reverse-sep (split-string words sep)) sep))
(mapconcat 'identity (reverse (split-string words sep) ) sep) )
 
(defun reverse-chars (line)
(reverse-sep line "") )
 
(defun reverse-words (line)
(reverse-sep line " ") )
 
(defvar line "rosetta code phrase reversal")
(progn
 
(setq line "rosetta code phrase reversal")
(with-output-to-temp-buffer "*reversals*"
(insert (format "%s\n"princ (reverse-chars line) ))
(terpri)
(princ (mapconcat 'identity (mapcar #'reverse-chars
(insert (format "%s\n"
(split-string line)) " "))
(mapconcat 'identity (mapcar #'reverse-chars
(terpri)
(split-string line) ) " ") ))
(princ (reverse-words line))
(terpri))</syntaxhighlight>
(insert (format "%s\n" (reverse-words line) )))
 
</lang>
{{out}}
<b>Output:</b>
 
<pre>
lasrever esarhp edoc attesor
attesor edoc esarhp lasrever
reversal phrase code rosetta
</pre>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">
USE: splitting
 
Line 805 ⟶ 1,262:
 
"rosetta code phrase reversal" [ reverse-string ] [ reverse-words ] [ reverse-phrase ] tri
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 818 ⟶ 1,275:
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.
 
F90 allows a WHILE-loop, and writing something like <langsyntaxhighlight Fortranlang="fortran"> DO WHILE (L1.LE.L .AND. ATXT(L1).LE." ")
L1 = L1 + 1
END DO</langsyntaxhighlight>
Would be rather more structured and involve fewer GO TOs and their labels, but alas, modern Fortran specifies that there is no specification as to whether or not both terms of an expression such as (A '''and''' B) will always be evaluated or instead there will be a shortcut: if A is ''false'' then the B term is ignored. And here, the A term checks whether or not L1 is within bounds and if it is not, then the B term should not be evaluated, not just because of the waste of effort but because to do so might involve accessing outside the definition of ATXT. As when the scan chases through the trailing spaces. One could make the array one longer, or rather, <code>L = LEN(TEXT) - 1</code> for this case but that would be messy, require explanation, be easily forgotten, and, typical ad-hoc testing would be unlikely to detect the mistake.
 
Alternatively, a GO TO can be removed from view by using EXIT in its place: <langsyntaxhighlight Fortranlang="fortran"> DO L1 = L1,L
IF (ATXT(L1).GT." ") EXIT
END DO</langsyntaxhighlight> Except that this relies on the index variable retaining its value on exiting the loop, either as fingering the first non-blank or, being L + 1. This expectation is frowned upon in some quarters.
 
Both variants would have to be followed by a test such as <code>IF (L1 .LE. L) THEN</code> to identify whether the start of a word has been found that would require further processing. So, all in all, suck up the GO TOs...<langsyntaxhighlight Fortranlang="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.
Line 867 ⟶ 1,324:
 
22 FORMAT (A36,":",66A1)
END</langsyntaxhighlight>
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 <langsyntaxhighlight Fortranlang="fortran"> WRITE (6,22) RW//RO,(" ",(ATXT(J), J = LST(I),IST(I),-1), I = 1,N,+1)</langsyntaxhighlight>
 
And the output is...
Line 880 ⟶ 1,337:
</pre>
 
=={{header|FreeBASICFrink}}==
The built-in <CODE>reverse</CODE> function reverses a string or the elements of a list.
<lang freebasic>' FB 1.05.0 Win64
 
Frink's built-in <CODE>reverse[''string'']</CODE> is quite smart and uses a grapheme-based algorithm to handle Unicode correctly. That is, it preserves "user-perceived characters" that may consist of characters, combining accents, high-plane Unicode characters (that is, above U+FFFF,) surrogate pairs, ''etc.'' correctly.
Sub split (s As Const String, sepList As Const String, result() As String)
If s = "" OrElse sepList = "" Then
Redim result(0)
result(0) = s
Return
End If
Dim As Integer i, j, count = 0, empty = 0, length
Dim As Integer position(Len(s) + 1)
position(0) = 0
For i = 0 To len(s) - 1
For j = 0 to Len(sepList) - 1
If s[i] = sepList[j] Then
count += 1
position(count) = i + 1
End If
Next j
Next i
Redim result(count)
If count = 0 Then
result(0) = s
Return
End If
position(count + 1) = len(s) + 1
For i = 1 To count + 1
length = position(i) - position(i - 1) - 1
result(i - 1) = Mid(s, position(i - 1) + 1, length)
Next
End Sub
 
Many languages will not work correctly with upper-plane Unicode characters because they are represented as Unicode "surrogate pairs" which are represented as two characters in a UTF-16 stream.
Function reverse(s As Const String) As String
If s = "" Then Return ""
Dim t As String = s
Dim length As Integer = Len(t)
For i As Integer = 0 to length\2 - 1
Swap t[i], t[length - 1 - i]
Next
Return t
End Function
 
For example, the string "g\u0308o" represents a g with combining diaeresis, followed by the letter o. Or, in other words, "g̈o". Note that while there are three Unicode codepoints, only two "graphemes" are displayed. Using Frink's smart "reverse" function preserves these combined graphemes. A naive reverse would move the diaeresis over the o instead of the g.
Dim s As String = "rosetta code phrase reversal"
Dim a() As String
Dim sepList As String = " "
 
Frink also has smart, human-language aware functions for splitting a string into a list of words. It correctly handles hyphenated words, numbers, and punctuation. It also has a built-in smart <CODE>reverseWords</CODE> function to reverse the words in a string.
Print "Original string => "; s
 
Print "Reversed string => "; reverse(s)
<syntaxhighlight lang="frink">a = "rosetta code phrase reversal"
Print "Reversed words => ";
println[reverse[a]]
split s, sepList, a()
println[join["", map["reverse", wordList[a]]]]
For i As Integer = LBound(a) To UBound(a)
println[reverseWords[a]] // Built-in function
Print reverse(a(i)); " ";
// Alternately, the above could be
Next
// join["", reverse[wordList[a]]]
Print
</syntaxhighlight>
Print "Reversed order => ";
For i As Integer = UBound(a) To LBound(a) Step -1
Print a(i); " ";
Next
Print : Print
Print "Press any key to quit"
Sleep</lang>
 
{{out}}
<pre>
lasrever esarhp edoc attesor
Original string => rosetta code phrase reversal
Reversedattesor stringedoc =>esarhp lasrever esarhp edoc attesor
reversal phrase code rosetta
Reversed words => attesor edoc esarhp lasrever
Reversed order => reversal phrase code rosetta
</pre>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=77cb8b3386a0f57524bdbff6634387cd Click this link to run this code]'''
<lang gambas>Public Sub Main()
Dim sString As String = "rosetta code phrase reversal" 'The string
Dim sNewString, sTemp As String 'String variables
Dim siCount As Short 'Counter
Dim sWord As New String[] 'Word store
 
For siCount = Len(sString) DownTo 1 'Loop backwards through the string
sNewString &= Mid(sString, sicount, 1) 'Add each character to the new string
Next
 
Print "Original string = \t" & sString & "\n" & 'Print the original string
"Reversed string = \t" & sNewString 'Print the reversed string
 
sNewString = "" 'Reset sNewString
 
For Each sTemp In Split(sString, " ") 'Split the original string by the spaces
sWord.Add(sTemp) 'Add each word to sWord array
Next
 
For siCount = sWord.max DownTo 0 'Loop backward through each word in sWord
sNewString &= sWord[siCount] & " " 'Add each word to to sNewString
Next
 
Print "Reversed word order = \t" & sNewString 'Print reversed word order
 
sNewString = "" 'Reset sNewString
For Each sTemp In sWord 'For each word in sWord
For siCount = Len(sTemp) DownTo 1 'Loop backward through the word
sNewString &= Mid(sTemp, siCount, 1) 'Add the characters to sNewString
Next
sNewString &= " " 'Add a space at the end of each word
Next
 
Print "Words reversed = \t" & sNewString 'Print words reversed
 
End</lang>
Output:
<pre>
Original string = rosetta code phrase reversal
Reversed string = lasrever esarhp edoc attesor
Reversed word order = reversal phrase code rosetta
Words reversed = attesor edoc esarhp lasrever
</pre>
 
=={{header|Go}}==
===Simple===
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,036 ⟶ 1,399:
}
fmt.Println("Word order reversed:", strings.Join(ws, " "))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,044 ⟶ 1,407:
</pre>
===Alternative===
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,097 ⟶ 1,460:
fmt.Println("Words reversed: ", reverseWords(phrase))
fmt.Println("Word order reversed:", reverseWordOrder(phrase))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,106 ⟶ 1,469:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def phaseReverse = { text, closure -> closure(text.split(/ /)).join(' ')}
 
def text = 'rosetta code phrase reversal'
Line 1,112 ⟶ 1,475:
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() } }"</langsyntaxhighlight>
{{out}}
<pre>Original: rosetta code phrase reversal
Line 1,120 ⟶ 1,483:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">reverseString, reverseEachWord, reverseWordOrder :: String -> String
reverseString = reverse
 
Line 1,134 ⟶ 1,497:
(putStrLn . unlines) $
[reverseString, reverseEachWord, reverseWordOrder] <*>
["rosetta code phrase reversal"]</langsyntaxhighlight>
{{Out}}
<pre>lasrever esarhp edoc attesor
Line 1,140 ⟶ 1,503:
reversal phrase code rosetta</pre>
 
=={{header|IS-BASICInsitux}}==
<syntaxhighlight lang="insitux">
<lang IS-BASIC>100 PROGRAM "ReverseS.bas"
(let phrase "rosetta code phrase reversal")
110 LET S$="Rosetta Code Pharse Reversal"
 
120 PRINT S$
(print (reverse phrase))
130 PRINT REVERSE$(S$)
(-> phrase (split " ") (map reverse) (join " ") print)
140 PRINT REVERSEW$(S$)
(-> phrase (split " ") reverse (join " ") print)
150 PRINT REVERSEC$(S$)
</syntaxhighlight>
160 DEF REVERSE$(S$)
{{out}}
170 LET T$=""
<pre>
180 FOR I=LEN(S$) TO 1 STEP-1
lasrever esarhp edoc attesor
190 LET T$=T$&S$(I)
attesor edoc esarhp lasrever
200 NEXT
reversal phrase code rosetta
210 LET REVERSE$=T$
null
220 END DEF
</pre>
230 DEF REVERSEW$(S$)
240 LET T$="":LET PE=LEN(S$)
250 FOR PS=PE TO 1 STEP-1
260 IF PS=1 OR S$(PS)=" " THEN LET T$=T$&" ":LET T$=T$&LTRIM$(S$(PS:PE)):LET PE=PS-1
270 NEXT
280 LET REVERSEW$=LTRIM$(T$)
290 END DEF
300 DEF REVERSEC$(S$)
310 LET T$="":LET PS=1
320 FOR PE=1 TO LEN(S$)
330 IF PE=LEN(S$) OR S$(PE)=" " THEN LET T$=T$&" ":LET T$=T$&REVERSE$(RTRIM$(S$(PS:PE))):LET PS=PE+1
340 NEXT
350 LET REVERSEC$=LTRIM$(T$)
360 END DEF</lang>
 
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight lang="j"> getWords=: (' '&splitstring) :. (' '&joinstring)
reverseString=: |.
reverseWords=: |.&.>&.getWords
reverseWordOrder=: |.&.getWords</langsyntaxhighlight>
'''Usage:'''
<langsyntaxhighlight lang="j"> phrase=: 'rosetta code phrase reversal'
(reverseWordOrder , reverseWords ,: reverseString) phrase
reversal phrase code rosetta
attesor edoc esarhp lasrever
lasrever esarhp edoc attesor</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">import java.util.Arrays;
 
public class PhraseRev{
Line 1,219 ⟶ 1,569:
System.out.println("Reversed word order: " + join(reverse(str.split(" ")), " "));
}
}</langsyntaxhighlight>
{{out}}
<pre>Straight-up reversed: lasrever esarhp edoc attesor
Line 1,227 ⟶ 1,577:
=={{header|JavaScript}}==
===ES5===
<langsyntaxhighlight JavaScriptlang="javascript">(function (p) {
return [
p.split('').reverse().join(''),
Line 1,239 ⟶ 1,589:
].join('\n');
 
})('rosetta code phrase reversal');</langsyntaxhighlight>
{{out}}
<pre>lasrever esarhp edoc attesor
Line 1,246 ⟶ 1,596:
 
===ES6===
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict'
 
Line 1,310 ⟶ 1,660:
], ["rosetta code phrase reversal"])
);
})();</langsyntaxhighlight>
{{Out}}
<pre>lasrever esarhp edoc attesor
Line 1,318 ⟶ 1,668:
=={{header|jq}}==
{{works with|jq|1.4}}
<langsyntaxhighlight lang="jq">def reverse_string: explode | reverse | implode;
 
"rosetta code phrase reversal"
Line 1,325 ⟶ 1,675:
"1. string reversed: \(reverse_string)",
"2. each word reversed: \($words | map(reverse_string) | join(" "))",
"3. word-order reversed: \($words | reverse | join(" "))"</langsyntaxhighlight>
{{out}}
$ jq -r -n -f Phrase_reversals.jq
Line 1,334 ⟶ 1,684:
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">
<lang Julia>
s = "rosetta code phrase reversal"
 
Line 1,351 ⟶ 1,701:
t = join(reverse(split(s, " ")), " ")
println(" ", t)
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,366 ⟶ 1,716:
 
=={{header|K}}==
<syntaxhighlight lang="k">
<lang K>
/ Rosetta code phrase reversal
/ phraserev.k
Line 1,375 ⟶ 1,725:
revwordorder: {rw:""; while[~(x~""); x: getnxtwd x;rw:" ",rw;rw:w,rw];:-1 _ rw}
 
</syntaxhighlight>
</lang>
The output of a session is given below:
{{out}}
Line 1,392 ⟶ 1,742:
 
</pre>
 
=={{header|Klingphix}}==
<syntaxhighlight lang="klingphix">include ..\Utilitys.tlhy
"Rosetta Code Phrase Reversal" dup ?
dup reverse ?
split dup reverse len [drop pop swap print " " print] for drop nl
len [drop pop swap reverse print " " print] for drop nl nl
 
"End " input</syntaxhighlight>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">
<lang scala>// version 1.0.6
 
fun reverseEachWord(s: String) = s.split(" ").mapjoinToString(" ") { it.reversed() }.joinToString(" ")
fun reverseWordOrder(s: String) = s.split(" ").reversed().joinToString(" ")
 
fun main(args: Array<String>) {
Line 1,404 ⟶ 1,765:
println("Reversed string => $reversed")
println("Reversed words => ${reverseEachWord(original)}")
// Either:
println("Reversed order => ${reverseWordOrder(original)}")
// Or:
println("Reversed order => ${reverseEachWord(reversed)}")
}</langsyntaxhighlight>
 
{{out}}
Line 1,414 ⟶ 1,778:
Reversed order => reversal phrase code rosetta
</pre>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="lisp">
{W.reverse word} reverses characters in a word
{S.reverse words} reverses a sequence of words
{S.map function words} applies a function to a sequence of words
{def S rosetta code phrase reversal} = rosetta code phrase reversal
 
{W.reverse {S}} -> lasrever esarhp edoc attesor
{S.map W.reverse {S}} -> attesor edoc esarhp lasrever
{S.reverse {S}} -> reversal phrase code rosetta
</syntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">-- Return a copy of table t in which each string is reversed
function reverseEach (t)
local rev = {}
Line 1,442 ⟶ 1,819:
print("1. " .. str:reverse())
print("2. " .. table.concat(reverseEach(tab), " "))
print("3. " .. table.concat(tabReverse(tab), " "))</langsyntaxhighlight>
{{out}}
<pre>1. lasrever esarhp edoc attesor
Line 1,449 ⟶ 1,826:
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">#reverse the string
str := "rosetta code phrase reversal":
print(StringTools:-Reverse(str)):
Line 1,459 ⟶ 1,836:
print(StringTools:-Join(convert(lst,list)," ")):
#reverse word order
print(StringTools:-Join(ListTools:-Reverse(StringTools:-Split(str," ")), " ")):</langsyntaxhighlight>
{{Out|Output}}
<pre> "lasrever esarhp edoc attesor"
Line 1,466 ⟶ 1,843:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">phrase = "Rosetta Code Phrase Reversal";
 
reverseWords[phrase_String] :=
Line 1,478 ⟶ 1,855:
 
{phrase, reverseWords@phrase, reverseLetters@phrase,
reverseWords@reverseLetters@phrase} // TableForm</langsyntaxhighlight>
 
{{out}}<pre>
Line 1,485 ⟶ 1,862:
attesoR edoC esarhP lasreveR
lasreveR esarhP edoC attesoR
</pre>
 
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang="matlab">
function r=revstr(s,d)
slist=strsplit(s,d);
for k=1:length(slist)
rlist{k}=slist{k}(end:-1:1);
end;
fprintf(1,'%s\n',s)
fprintf(1,'%s %c',slist{end:-1:1},d)
fprintf(1,'\n');
fprintf(1,'%s %c',rlist{:},d)
fprintf(1,'\n');
fprintf(1,'%s\n',s(end:-1:1))
end
 
revstr('Rosetta Code Phrase Reversal', ' ')
</syntaxhighlight>
 
 
{{out}}
<pre>
Rosetta Code Phrase Reversal
Reversal Phrase Code Rosetta
attesoR edoC esarhP lasreveR
lasreveR esarhP edoC attesoR
 
</pre>
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">phrase = "rosetta code phrase reversal"
 
// general sequence reversal function
Line 1,512 ⟶ 1,917:
// 3. Reverse the order of each word of the string, maintaining the order of characters in each word.
print reverse(phrase.split).join
</syntaxhighlight>
</lang>
{{out}}
<pre>lasrever esarhp edoc attesor
Line 1,519 ⟶ 1,924:
 
=={{header|MUMPS}}==
<langsyntaxhighlight MUMPSlang="mumps">set string="Rosetta Code Phrase Reversal"
set str="",len=$length(string," ")
for i=1:1:len set $piece(str," ",i)=$piece(string," ",len-i+1)
Line 1,525 ⟶ 1,930:
write $reverse(string),!
write str,!
write $reverse(str),!</langsyntaxhighlight>
 
{{out}}<pre>Rosetta Code Phrase Reversal
Line 1,532 ⟶ 1,937:
attesoR edoC esarhP lasreveR
</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import algorithm, sequtils, strutils
 
const Phrase = "rosetta code phrase reversal"
 
echo "Phrase: ", Phrase
echo "Reversed phrase: ", reversed(Phrase).join()
echo "Reversed words: ", Phrase.split().mapIt(reversed(it).join()).join(" ")
echo "Reversed word order: ", reversed(Phrase.split()).join(" ")</syntaxhighlight>
 
If we prefer to avoid using modules “algorithm” and “sequtils” and produce somewhat more efficient (but also more verbose) code, here is another solution:
 
<syntaxhighlight lang="nim">import strutils
 
const Phrase = "rosetta code phrase reversal"
 
proc reversed(s: string): string =
for i in countdown(s.high, 0):
result.add s[i]
 
proc reversedWords(s: string): string =
let words = s.split()
result = reversed(words[0])
for i in 1..words.high:
result.add ' ' & reversed(words[i])
 
proc reversedWordOrder(s: string): string =
let words = s.split()
result = words[^1]
for i in countdown(words.high - 1, 0):
result.add ' ' & words[i]
 
echo "Phrase: ", Phrase
echo "Reversed phrase: ", reversed(Phrase)
echo "Reversed words: ", reversedWords(Phrase)
echo "Reversed word order: ", reversedWordOrder(Phrase)</syntaxhighlight>
 
{{out}}
<pre>Phrase: rosetta code phrase reversal
Reversed phrase: lasrever esarhp edoc attesor
Reversed words: attesor edoc esarhp lasrever
Reversed word order: reversal phrase code rosetta</pre>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">"rosetta code phrase reversal" reverse println
"rosetta code phrase reversal" words map(#reverse) unwords println
"rosetta code phrase reversal" words reverse unwords println</langsyntaxhighlight>
 
{{out}}
Line 1,548 ⟶ 1,996:
=={{header|Perl}}==
 
<langsyntaxhighlight lang="perl">use feature 'say';
my $s = "rosetta code phrase reversal";
 
Line 1,557 ⟶ 2,005:
 
# Or, using a regex:
say "2. Each word reversed : ", $s =~ s/[^ ]+/reverse $&/gre;</langsyntaxhighlight>
 
{{out}}
Line 1,569 ⟶ 2,017:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
I have assumed step 2 should be applied to the result of step 1, and step 3 applied to the result of step 2.<br>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Obviously I'm right and everyone else is wrong!
<langspan Phixstyle="color: #008080;">constant</span> <span style="color: #000000;">test</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"rosetta code phrase reversal"</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">fmt</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
?reverse(test)
The original phrase as given: %s
sequence words = split(reverse(test))
1. Reverse the entire phrase: %s
for i=1 to length(words) do
2. Reverse words, same order: %s
words[i] = reverse(words[i])
3. Reverse order, same words: %s
end for
"""</span>
?join(words)
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">test</span><span style="color: #0000FF;">,</span>
?join(reverse(words))</lang>
<span style="color: #7060A8;">reverse</span><span style="color: #0000FF;">(</span><span style="color: #000000;">test</span><span style="color: #0000FF;">),</span>
<span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #000000;">test</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">reverse</span><span style="color: #0000FF;">)),</span>
<span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">reverse</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #000000;">test</span><span style="color: #0000FF;">)))})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
The original phrase as given: rosetta code phrase reversal
"lasrever esarhp edoc attesor"
1. Reverse the entire phrase: lasrever esarhp edoc attesor
"reversal phrase code rosetta"
2. Reverse words, same order: attesor edoc esarhp lasrever
"rosetta code phrase reversal"
3. Reverse order, same words: reversal phrase code rosetta
</pre>
 
=={{header|Phixmonti}}==
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt
<lang Phixmonti>"Rosetta Code Phrase Reversal" dup print nl
 
"Rosetta Code Phrase Reversal" dup print nl
dup reverse print nl
split dup reverse len for . headpop swap print " " print tail nip endfor . nl
len for drop. headpop swap reverse print " " print tail nip endfor drop.</langsyntaxhighlight>
{{out}}
<pre>Rosetta Code Phrase Reversal
Line 1,598 ⟶ 2,053:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
// Initialize a variable with the input desired
$strin = "rosetta code phrase reversal";
Line 1,626 ⟶ 2,081:
// Show the reversal of the word order while leaving the words in order
echo "Word order reversed: ".$str_word_order_reversed."\n";
</syntaxhighlight>
</lang>
 
<pre>Input: rosetta code phrase reversal
Line 1,632 ⟶ 2,087:
Words reversed: attesor edoc esarhp lasrever
Word order reversed: reversal phrase code rosetta</pre>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">import util.
 
go =>
S = "rosetta code phrase reversal",
println(S),
println(reverse(S)),
println([reverse(W) : W in S.split()].join(' ')),
println(reverse(S.split()).join(' ')),
nl.</syntaxhighlight>
 
{{out}}
<pre>rosetta code phrase reversal
lasrever esarhp edoc attesor
attesor edoc esarhp lasrever
reversal phrase code rosetta</pre>
 
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(let (S (chop "rosetta code phrase reversal") L (split S " "))
(prinl (reverse S))
(prinl (glue " " (mapcar reverse L)))
(prinl (glue " " (reverse L))) )</langsyntaxhighlight>
Output:
<pre>lasrever esarhp edoc attesor
Line 1,644 ⟶ 2,117:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
reverser: procedure options (main); /* 19 August 2015 */
declare (phrase, r, word) character (100) varying;
Line 1,666 ⟶ 2,139:
 
end reverser;
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,676 ⟶ 2,149:
 
=={{header|plainTeX}}==
<langsyntaxhighlight lang="tex">\def\afterfi#1#2\fi{#2\fi#1}
\def\RevSingleWord#1{\RevSingleWordi{}#1\RSWA\RSWB\RSWB\RSWB\RSWB\RSWB\RSWB\RSWB\RSWB\RSWA}
\def\RevSingleWordi#1#2#3#4#5#6#7#8#9{\RSWgobtoB#9\RSWend\RSWB\RevSingleWordi{#9#8#7#6#5#4#3#2#1}}
\def\RSWend\RSWB\RevSingleWordi#1#2\RSWA{\RSWgobtoA#1}
\def\RSWgobtoA#1\RSWA{}\def\RSWgobtoB#1\RSWB{}
\def\RSWgobtoB#1\RSWB{}
%---
\def\firstchartonil#1#2\nil{#1}
\def\RevOrderSameWords#1{\RevOrderSameWordsi{}#1 \. \* \* \* \* \* \* \* \* \.}
\def\RevOrderSameWordsi#1#2 #3 #4 #5 #6 #7 #8 #9 {%
\expandafter\ifx\expandafter\*\firstchartonil#9\nil
\expandafter\ROSWend\else\expandafter\RevOrderSameWordsi\fi{#9 #8 #7 #6 #5 #4 #3 #2#1}%
}
\def\ROSWend#1#2\.{\ROSWendi#1}
Line 1,694 ⟶ 2,168:
\def\RevOnlyWords#1{\edef\ROWtemp{\noexpand\RevOnlyWordsi{}#1 \noexpand\ROWquark\space}\ROWtemp}
\def\RevOnlyWordsi#1#2 {%
\ifx\ROWquark#2\afterfi{\ROWgoblastspace#1\nil}%
\else\afterfi{\RevOnlyWordsi{#1\RevSingleWord{#2} }}%
\fi
}
\def\ROWgoblastspace#1 \nil{#1}
Line 1,702 ⟶ 2,176:
\def\RevAll#1{\RevAlli{}#1 \. \* \* \* \* \* \* \* \* \.\:}
\def\RevAlli#1#2 #3 #4 #5 #6 #7 #8 #9 {%
\expandafter\ifx\expandafter\*\firstchartonil#9\nil
\expandafter\RAWend\else\expandafter\RevAlli\fi{#9 #8 #7 #6 #5 #4 #3 #2#1}%
}
\def\RAWend#1#2\.{\RAWendi#1}
Line 1,714 ⟶ 2,188:
Reverse order, same words&\RevOrderSameWords{rosetta code phrase reversal}\cr
Reverse only words&\RevOnlyWords{rosetta code phrase reversal}\cr\crcr}
\bye</langsyntaxhighlight>
 
pdf or dvi output looks like:
Line 1,724 ⟶ 2,198:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function reverse($a, $sep = "") {
if($a.Length -gt 0) {
Line 1,738 ⟶ 2,212:
$task2
$task3
</langsyntaxhighlight>
<b>Output:</b>
<pre>
Line 1,745 ⟶ 2,219:
reversal phrase code rosetta
</pre>
 
=={{header|PureBasic}}==
<lang PureBasic>#TEXT="rosetta code phrase reversal"
 
If OpenConsole("rosetta code phrase reversal")
Define idx.i=1, txt.s=""
Print(~"Original:\t\t")
PrintN(#TEXT)
Print(~"Reversed:\t\t")
PrintN(ReverseString(#TEXT))
Print(~"Reversed words:\t\t")
txt=StringField(#TEXT,idx," ")
While Len(txt)
Print(ReverseString(txt)+" ")
idx+1
txt=StringField(#TEXT,idx," ")
Wend
PrintN("")
Print(~"Reversed order:\t\t")
idx-1
txt=StringField(#TEXT,idx," ")
While Len(txt)
Print(txt+" ")
If idx>1 : idx-1 : Else : Break : EndIf
txt=StringField(#TEXT,idx," ")
Wend
Input()
EndIf</lang>
{{out}}
<pre>Original: rosetta code phrase reversal
Reversed: lasrever esarhp edoc attesor
Reversed words: attesor edoc esarhp lasrever
Reversed order: reversal phrase code rosetta</pre>
 
=={{header|Python}}==
These examples use the [https://docs.python.org/2/whatsnew/2.3.html#extended-slices extended slicing] notation of <code>[::-1]</code> to reverse strings and lists of strings:
<langsyntaxhighlight lang="python">>>> phrase = "rosetta code phrase reversal"
>>> phrase[::-1] # Reversed.
'lasrever esarhp edoc attesor'
Line 1,793 ⟶ 2,229:
>>> ' '.join(phrase.split()[::-1]) # Word order reversed.
'reversal phrase code rosetta'
>>> </langsyntaxhighlight>
 
 
Or, variously composing three reusable abstractions – '''reverse''', '''words''', and '''unwords''':
 
<langsyntaxhighlight lang="python">'''String reversals at different levels.'''
 
 
Line 1,886 ⟶ 2,322:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>rosetta code phrase reversal:
Line 1,893 ⟶ 2,329:
wordsWithReversedCharacters -> 'attesor edoc esarhp lasrever'
reversedWordOrder -> 'reversal phrase code rosetta'</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> $ "rosetta code phrase reversal"
 
3 times dup
 
say "0. " echo$ cr
say "1. " reverse echo$ cr
say "2. " nest$ witheach [ reverse echo$ sp ] cr
say "3. " nest$ reverse witheach [ echo$ sp ] cr</syntaxhighlight>
 
{{out}}
 
<pre>0. rosetta code phrase reversal
1. lasrever esarhp edoc attesor
2. attesor edoc esarhp lasrever
3. reversal phrase code rosetta </pre>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">#lang racket/base
(require
(only-in srfi/13 string-reverse)
Line 1,907 ⟶ 2,361:
(string-join (reverse (string-split s)))))
 
(for-each displayln (phrase-reversal "rosetta code phrase reversal"))</langsyntaxhighlight>
 
{{out}}
Line 1,916 ⟶ 2,370:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>my $s = 'rosetta code phrase reversal';
 
put 'Input : ', $s;
put 'String reversed : ', $s.flip;
put 'Each word reversed : ', $s.words».flip;
put 'Word-order reversed : ', $s.words.reverse;</langsyntaxhighlight>
{{out}}
<pre>Input : rosetta code phrase reversal
Line 1,927 ⟶ 2,381:
Each word reversed : attesor edoc esarhp lasrever
Word-order reversed : reversal phrase code rosetta</pre>
 
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
, 'rosetta code phrase reversal': e.Str
= <Prout <Reverse e.Str>>
<Prout <Join <Each Reverse <Split e.Str>>>>
<Prout <Join <Reverse <Split e.Str>>>>;
};
 
Reverse {
= ;
t.X e.Y = <Reverse e.Y> t.X;
};
 
Split {
(e.X) = (e.X);
(e.X) ' ' e.Y = (e.X) <Split () e.Y>;
(e.X) s.C e.Y = <Split (e.X s.C) e.Y>;
e.X = <Split () e.X>;
};
 
Join {
= ;
(e.X) = e.X;
(e.X) e.Y = e.X ' ' <Join e.Y>;
};
 
Each {
s.F = ;
s.F (e.X) e.Y = (<Mu s.F e.X>) <Each s.F e.Y>;
};</syntaxhighlight>
{{out}}
<pre>lasrever esarhp edoc attesor
attesor edoc esarhp lasrever
reversal phrase code rosetta</pre>
 
=={{header|REXX}}==
===version 1===
Working with REXX (strings and words) is trivial.
<langsyntaxhighlight lang="rexx">s='rosetta code phrase reversal'
r1=reverse(s)
r2=''
Line 1,946 ⟶ 2,435:
say "string reversed : " r1
say "each word reversed : " r2
say "word-order reversed : " r3</langsyntaxhighlight>
{{out}}
<pre>input : rosetta code phrase reversal
Line 1,954 ⟶ 2,443:
 
===version 2===
<langsyntaxhighlight lang="rexx">/*REXX program reverses words and also letters in a string in various (several) ways. */
parse arg $ /*obtain optional arguments from the CL*/
if $='' then $= "rosetta code phrase reversal" /*Not specified? Then use the default.*/
Line 1,964 ⟶ 2,453:
say ' original phrase reversed: ' reverse($)
say ' reversed individual words: ' strip(L)
say ' reversed words in phrases: ' W /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input string:}}
<pre>
Line 1,974 ⟶ 2,463:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
aString = "Welcome to the Ring Language"
bString = ""
Line 1,984 ⟶ 2,473:
next
return bString
</syntaxhighlight>
</lang>
 
Output:
Line 1,992 ⟶ 2,481:
 
=={{header|Ruby}}==
<langsyntaxhighlight 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.</langsyntaxhighlight>
 
{{out}}
Line 2,006 ⟶ 2,495:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn reverse_string(string: &str) -> String {
string.chars().rev().collect::<String>()
}
Line 2,057 ⟶ 2,546:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">object PhraseReversals extends App {
val phrase = scala.io.StdIn.readLine
println(phrase.reverse)
println(phrase.split(' ').map(_.reverse).mkString(" "))
println(phrase.split(' ').reverse.mkString(" "))
}</langsyntaxhighlight>
 
{{out}}
Line 2,075 ⟶ 2,564:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 2,094 ⟶ 2,583:
end for;
writeln("Reverse order, same words:" rpad 27 <& join(wordList, ' '));
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,102 ⟶ 2,591:
Reverse words, same order: attesor edoc esarhp lasrever
Reverse order, same words: reversal phrase code rosetta
</pre>
 
=={{header|SenseTalk}}==
<syntaxhighlight lang="sensetalk">set phrase to "rosetta code phrase reversal"
put phrase reversed
put (the reverse of each word of phrase) joined by space
put (each word of phrase) reversed joined by space
</syntaxhighlight>
{{out}}
<pre>
lasrever esarhp edoc attesor
attesor edoc esarhp lasrever
reversal phrase code rosetta
</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight 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</langsyntaxhighlight>
{{out}}
<pre>lasrever esarhp edoc attesor
attesor edoc esarhp lasrever
reversal phrase code rosetta</pre>
 
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
<syntaxhighlight lang="smalltlak">|str|
str := 'rosetta code phrase reversal'.
 
Transcript showCR:(str reversed).
Transcript showCR:(((str splitBy:$ ) collect:#reversed) join:$ ).
Transcript showCR:(((str splitBy:$ ) reversed) join:$ ).</syntaxhighlight>
{{out}}
<pre>lasrever esarhp edoc attesor
Line 2,116 ⟶ 2,631:
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">
func reverseString(s:String)->String{
var temp = [Character]()
Line 2,155 ⟶ 2,670:
print(reverseWord(s:str))
print(flipString(s:str))
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">set s "rosetta code phrase reversal"
# Reverse all characters
puts [string reverse $s]
Line 2,164 ⟶ 2,679:
puts [lmap word $s {string reverse $word}]
# Reverse the words but not the characters
puts [lreverse $s]</langsyntaxhighlight>
{{out}}
<pre>
Line 2,178 ⟶ 2,693:
{{works with|bash}}
{{works with|ksh93}}
<langsyntaxhighlight lang="sh">s1="rosetta code phrase reversal"
echo "Original string ----------------------> "$s1
 
Line 2,191 ⟶ 2,706:
while [ $word_num != 0 ];do
echo -n $(echo $s1|cut -d " " -f $word_num);echo -n " "
word_num=$(expr $word_num - 1);done;echo</langsyntaxhighlight>
 
{{out}}
Line 2,205 ⟶ 2,720:
{{works with|bash}}
{{works with|ksh93}}
<langsyntaxhighlight lang="sh">s1="rosetta code phrase reversal"
echo "Original string --> "$s1
 
Line 2,230 ⟶ 2,745:
while [ $word_num != 0 ];do
echo -n $(echo $s1|cut -d " " -f $word_num);echo -n " "
word_num=$(expr $word_num - 1);done;echo</langsyntaxhighlight>
 
{{out}}
Line 2,238 ⟶ 2,753:
3.) Reverse word order --> reversal phrase code rosetta</pre>
 
=={{header|VBAV (Vlang)}}==
<syntaxhighlight lang="v (vlang)">
fn main() {
str := 'rosetta code phrase reversal'
words := str.fields()
println('Original: $str')
println('Reverse: ${str.reverse()}')
println('Char-Word Reverse: ${words.map(it.reverse()).join(' ')}')
println('Word Reverse: ${words.reverse().join(' ')}')
}</syntaxhighlight>
{{out}}
<pre>Original: rosetta code phrase reversal
Reverse: lasrever esarhp edoc attesor
Char-Word Reverse: attesor edoc esarhp lasrever
Word Reverse: reversal phrase code rosett</pre>
 
=={{header|Wren}}==
<lang vb>
<syntaxhighlight lang="wren">var s = "rosetta code phrase reversal"
Option Explicit
System.print("Input : %(s)")
System.print("String reversed : %(s[-1..0])")
System.print("Each word reversed : %(s.split(" ").map { |w| w[-1..0] }.join(" "))")
System.print("Word order reversed : %(s.split(" ")[-1..0].join(" "))")</syntaxhighlight>
 
Sub Main_Phrase_Reversals()
Const PHRASE As String = "rosetta code phrase reversal"
Debug.Print "Original String : " & PHRASE
Debug.Print "Reverse String : " & Reverse_String(PHRASE)
Debug.Print "Reverse each individual word : " & Reverse_each_individual_word(PHRASE)
Debug.Print "Reverse order of each word : " & Reverse_the_order_of_each_word(PHRASE)
End Sub
 
Function Reverse_String(strPhrase As String) As String
Reverse_String = StrReverse(strPhrase)
End Function
 
Function Reverse_each_individual_word(strPhrase As String) As String
Dim Words, i&, strTemp$
Words = Split(strPhrase, " ")
For i = 0 To UBound(Words)
Words(i) = Reverse_String(CStr(Words(i)))
Next i
Reverse_each_individual_word = Join(Words, " ")
End Function
 
Function Reverse_the_order_of_each_word(strPhrase As String) As String
Dim Words, i&, strTemp$
 
Words = Split(strPhrase, " ")
For i = UBound(Words) To 0 Step -1
strTemp = strTemp & " " & Words(i)
Next i
Reverse_the_order_of_each_word = Trim(strTemp)
End Function
</lang>
{{out}}
<pre>Original String : rosetta code phrase reversal
Reverse String : lasrever esarhp edoc attesor
Reverse each individual word : attesor edoc esarhp lasrever
Reverse order of each word : reversal phrase code rosetta</pre>
 
=={{header|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>
{{Out}}
<pre>
OriginalInput String : rosetta code phrase reversal
Reverse String reversed : lasrever esarhp edoc attesor
ReverseEach Stringword Eachreversed Word : attesor edoc esarhp lasrever
Reverse Phrase Word order reversed : reversal phrase code rosetta
</pre>
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">phrase$ = "Rosetta Code Phrase Reversal"
 
dim word$(1)
Line 2,364 ⟶ 2,819:
return rw$
end sub</langsyntaxhighlight>
{{out}}
<pre>Rosetta Code Phrase Reversal
Line 2,372 ⟶ 2,827:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">zkl: var str="rosetta code phrase reversal"
rosetta code phrase reversal
 
Line 2,382 ⟶ 2,837:
 
zkl: str.split().reverse().concat(" ") #3
reversal phrase code rosetta</langsyntaxhighlight>
2,094

edits