Reverse words in a string: Difference between revisions

Added Easylang
(Added Easylang)
 
(95 intermediate revisions by 59 users not shown)
Line 6:
 
;Example:
<ttbig><big><code>Hey you, Bub! </ttcode></big></big> &nbsp; would be shown reversed as: &nbsp; <ttbig><big><code> Bub! you, Hey </code></big></ttbig>
 
 
Tokens are any non-space characters separated by spaces (formally, white-space); &nbsp; the visible punctuation form part of the word within which it is located and should not be modified.
Line 12 ⟶ 13:
You may assume that there are no significant non-visible characters in the input. &nbsp; Multiple or superfluous spaces may be compressed into a single space.
 
Some strings have no tokens, so an empty string &nbsp; (or one just containing spaces) &nbsp; would be the result.
 
'''Display''' the strings in order &nbsp; (1<sup>st</sup>, 2<sup>nd</sup>, 3<sup>rd</sup>, ···), &nbsp; and one string per line.
 
(You can consider the ten strings as ten lines, and the tokens as words.)
Line 40 ⟶ 41:
* [[Phrase reversals]]
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V text =
‘---------- Ice and Fire ------------
 
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
 
... elided paragraph last ...
 
Frost Robert -----------------------’
 
L(line) text.split("\n")
print(reversed(line.split(‘ ’)).join(‘ ’))</syntaxhighlight>
 
{{out}}
<pre>
------------ Fire and Ice ----------
 
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
 
... last paragraph elided ...
 
----------------------- Robert Frost
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC Reverse(CHAR ARRAY src,dst)
BYTE i,j,k,beg,end
 
i=1 j=src(0)
WHILE j>0
DO
WHILE j>0 AND src(j)=$20
DO j==-1 OD
IF j=0 THEN
EXIT
ELSE
end=j
FI
WHILE j>0 AND src(j)#$20
DO j==-1 OD
beg=j+1
 
IF i>1 THEN
dst(i)=$20 i==+1
FI
 
FOR k=beg TO end
DO
dst(i)=src(k) i==+1
OD
OD
dst(0)=i-1
RETURN
 
PROC Test(CHAR ARRAY src)
CHAR ARRAY dst(40)
 
Reverse(src,dst)
PrintE(dst)
RETURN
 
PROC Main()
Test("---------- Ice and Fire ------------")
Test("")
Test("fire, in end will world the say Some")
Test("ice. in say Some")
Test("desire of tasted I've what From")
Test("fire. favor who those with hold I")
Test("")
Test("... elided paragraph last ...")
Test("")
Test("Frost Robert -----------------------")
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Reverse_words_in_a_string.png Screenshot from Atari 8-bit computer]
<pre>
------------ Fire and Ice ----------
 
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
 
... last paragraph elided ...
 
----------------------- Robert Frost
</pre>
 
=={{header|Ada}}==
Line 47 ⟶ 145:
To Split a string into words, we define a Package "Simple_Parse". This package is also used for the Phrase Reversal Task [[http://rosettacode.org/wiki/Phrase_reversals#Ada]].
 
<langsyntaxhighlight Adalang="ada">package Simple_Parse is
-- a very simplistic parser, useful to split a string into words
Line 57 ⟶ 155:
-- else Next_Word sets Point to S'Last+1 and returns ""
end Simple_Parse;</langsyntaxhighlight>
 
The implementation of "Simple_Parse":
 
<langsyntaxhighlight Adalang="ada">package body Simple_Parse is
function Next_Word(S: String; Point: in out Positive) return String is
Line 80 ⟶ 178:
end Next_Word;
end Simple_Parse;</langsyntaxhighlight>
 
===Main Program===
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Simple_Parse;
 
procedure Reverse_Words is
Line 104 ⟶ 202:
Put_Line(Reverse_Words(Get_Line)); -- poem is read from standard input
end loop;
end Reverse_Words;</langsyntaxhighlight>
 
=={{header|Aime}}==
<syntaxhighlight lang ="aime">integer i, j, s;
list l, x;
text s, t;
data b;
file f;
 
l = list("---------- Ice and Fire ------------",
l_bill(l, 0,
"---------- Ice and Fire ------------",
"fire, in end will world the say Some",
"fire,ice. in end will world the say Some",
"ice.desire of tasted inI've saywhat SomeFrom",
"desirefire. offavor tastedwho I'vethose whatwith Fromhold I",
"fire. favor who those with hold I",
"... elided paragraph last ...",
"... elided paragraph last ...",
"Frost Robert -----------------------",);
"Frost Robert -----------------------");
 
for (, t in l) {
i = -l_length(l);
file().b_affix(t).list(x, 0);
while (i) {
b_castfor (bj, l[i]s in x.reverse); {
o_space(sign(j));
f_b_affix(f, b);
f_list(f, x, 0 o_text(s);
j = l_length(x);
s = 0;
while (j) {
o_space(s);
s = 1;
o_text(x[j -= 1]);
}
o_newline();
}</syntaxhighlight>
i += 1;
}</lang>
{{out}}
<pre>------------ Fire and Ice ----------
Line 150 ⟶ 239:
 
----------------------- Robert Frost</pre>
 
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68"># returns original phrase with the order of the words reversed #
# a word is a sequence of non-blank characters #
PROC reverse word order = ( STRING original phrase )STRING:
Line 196 ⟶ 284:
print( ( reverse word order ( " " ), newline ) );
print( ( reverse word order ( "Frost Robert -----------------------" ), newline ) )
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 213 ⟶ 301:
=={{header|AppleScript}}==
 
<syntaxhighlight lang AppleScript="applescript">on run {}
unlines(map(_lines("---------- Ice and Fire ------------
 
unlines(map(reverseWords, |lines|("---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
 
... elided paragraph last ...
Frost Robert -----------------------")))
 
Frost Robert -----------------------"), reverseWords))
end run
 
 
-- String -> String
-- GENERIC FUNCTIONS ---------------------------------------------------------
 
-- reverseWords :: String -> String
on reverseWords(str)
unwords(_reverse|reverse|(_words|words|(str)))
end reverseWords
 
-- |reverse| :: [a] -> [a]
on _reverse|reverse|(xs)
if class of xs is text then
(reverse of characters of xs) as text
Line 240 ⟶ 331:
reverse of xs
end if
end _reverse|reverse|
 
-- |lines| :: Text -> [Text]
on _lines|lines|(str)
splitOn(linefeed, str)
end _lines|lines|
 
-- |words| :: Text -> [Text]
on _words|words|(str)
splitOn(space, str)
end _words|words|
 
-- ulines :: [Text] -> Text
on unlines(lstLines)
intercalate(linefeed, lstLines)
end unlines
 
-- unwords :: [Text] -> Text
on unwords(lstWords)
intercalate(space, lstWords)
end unwords
 
-- splitOn :: 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
 
-- interCalate :: 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
 
-- [a]map ->:: (a -> b) -> [a] -> [b]
on map(xsf, fxs)
set mf totell mReturn(f)
set lstlng to {}length of xs
set lng to length ofset lst to xs{}
repeat with i from 1 to lng
set end of lst to mf's calllambda(item i of xs, i, xs)
end repeat
return lst
end tell
end map
 
-- liftLift 2nd class handler function into 1st class wrapperscript wrapper
-- mReturn :: Handler -> Script
-- handler function --> first class script object
on mReturn(f)
if class of f is script mfthen
property call : f
end scriptelse
script
end mReturn</lang>
property lambda : f
end script
end if
end mReturn
</syntaxhighlight>
{{out}}
 
Line 310 ⟶ 407:
 
=={{header|Applesoft BASIC}}==
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">100 DATA"---------- ICE AND FIRE ------------"
110 DATA" "
120 DATA"FIRE, IN END WILL WORLD THE SAY SOME"
Line 336 ⟶ 433:
350 IF C$ <> " " THEN W$ = C$ + W$ : NEXT I
360 RETURN
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">text: {
---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------}
 
reversed: map split.lines text =>
[join.with:" " reverse split.words &]
 
print join.with:"\n" reversed</syntaxhighlight>
 
{{out}}
 
<pre>------------ Fire and Ice ----------
 
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
 
... last paragraph elided ...
 
----------------------- Robert Frost</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Data := "
(Join`r`n
---------- Ice and Fire ------------
Line 359 ⟶ 487:
Output .= Line "`n", Line := ""
}
MsgBox, % RTrim(Output, "`n")</langsyntaxhighlight>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f REVERSE_WORDS_IN_A_STRING.AWK
BEGIN {
Line 385 ⟶ 513:
exit(0)
}
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 396 ⟶ 524:
 
... last paragraph elided ...
 
----------------------- Robert Frost
</pre>
 
=={{header|BaCon}}==
<syntaxhighlight lang="qbasic">
PRINT REV$("---------- Ice and Fire ------------")
PRINT
PRINT REV$("fire, in end will world the say Some")
PRINT REV$("ice. in say Some ")
PRINT REV$("desire of tasted I've what From ")
PRINT REV$("fire. favor who those with hold I ")
PRINT
PRINT REV$("... elided paragraph last ... ")
PRINT
PRINT REV$("Frost Robert -----------------------")
</syntaxhighlight>
Using the REV$ function which takes a sentence as a delimited string where the items are separated by a delimiter (the space character is the default delimiter).
{{out}}
<pre>
------------ Fire and Ice ----------
 
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
 
... last paragraph elided ...
 
----------------------- Robert Frost
Line 401 ⟶ 557:
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">@echo off
 
::The Main Thing...
Line 435 ⟶ 591:
echo.%reversed%
goto :EOF
::/The Function...</langsyntaxhighlight>
{{Out}}
<pre>
Line 450 ⟶ 606:
 
</pre>
 
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">source = freefile
open (source, "m:\text.txt")
textEnt$ = ""
dim textSal$(size(source)*8)
linea = 0
 
while not eof(source)
textEnt$ = readline(source)
linea += 1
textSal$[linea] = textEnt$
end while
 
for n = size(source) to 1 step -1
print textSal$[n];
next n
close source</syntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> PRINT FNreverse("---------- Ice and Fire ------------")\
\ 'FNreverse("")\
\ 'FNreverse("fire, in end will world the say Some")\
Line 468 ⟶ 643:
LOCAL sp%
sp%=INSTR(s$," ")
IF sp% THEN =FNreverse(MID$(s$,sp%+1))+" "+LEFT$(s$,sp%-1) ELSE =s$</langsyntaxhighlight>
 
{{out}}
Line 482 ⟶ 657:
----------------------- Robert Frost</pre>
 
=={{header|BQN}}==
<syntaxhighlight lang="bqn">Split ← +`∘<⟜»⊸×⊸-⟜¬∘>⟜' '⊸⊔
Join ← (⊣∾' '∾⊢)´⍟(1<≡)
 
text ← ⍉≍⟨
"---------- Ice and Fire ------------"
""
"fire, in end will world the say Some"
"ice. in say Some "
"desire of tasted I've what From "
"fire. favor who those with hold I "
""
"... elided paragraph last ..."
""
"Frost Robert -----------------------"⟩
 
Join∘⌽∘Split¨ text</syntaxhighlight>
Alternative based on the approach described in [https://saltysylvi.github.io/blog/flat1.html this blog post]:
<syntaxhighlight lang="bqn">{(⍒+`∨⟜»' '=𝕩)⊏𝕩}¨ text</syntaxhighlight>
{{out}}
<pre>┌─
╵ "------------ Fire and Ice ----------"
⟨⟩
"Some say the world will end in fire,"
"Some say in ice."
"From what I've tasted of desire"
"I hold with those who favor fire."
⟨⟩
"... last paragraph elided ..."
⟨⟩
"----------------------- Robert Frost"
┘</pre>
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">("---------- Ice and Fire ------------
fire, in end will world the say Some
Line 520 ⟶ 727:
& !output reverse$!text:?output
& out$str$!output
);</langsyntaxhighlight>
{{out}}
<pre>------------ Fire and Ice ----------
Line 534 ⟶ 741:
 
=={{header|Burlesque}}==
<langsyntaxhighlight lang="blsq">
blsq ) "It is not raining"wd<-wd
"raining not is It"
blsq ) "ice. in say some"wd<-wd
"some say in ice."
</syntaxhighlight>
</lang>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <ctype.h>
 
Line 576 ⟶ 783:
 
return 0;
}</langsyntaxhighlight>
Output is the same as everyone else's.
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
 
public class ReverseWordsInString
{
public static void Main(string[] args)
{
string text = @"
---------- Ice and Fire ------------
 
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
 
... elided paragraph last ...
 
Frost Robert -----------------------
";
 
foreach (string line in text.Split(Environment.NewLine)) {
//Splits on any whitespace, not just spaces
string[] words = line.Split(default(char[]), StringSplitOptions.RemoveEmptyEntries);
Array.Reverse(words);
WriteLine(string.Join(" ", words));
}
}
}</syntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <algorithm>
#include <functional>
Line 641 ⟶ 877:
return 0;
}
</syntaxhighlight>
</lang>
 
===Alternate version===
<langsyntaxhighlight lang="cpp">
#include <string>
#include <iostream>
Line 685 ⟶ 921:
return system( "pause" );
}
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">
(def poem
"---------- Ice and Fire ------------
Line 703 ⟶ 939:
(dorun
(map println (map #(apply str (interpose " " (reverse (re-seq #"[^\s]+" %)))) (clojure.string/split poem #"\n"))))
</syntaxhighlight>
</lang>
Output is the same as everyone else's.
 
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
<lang COBOL>
program-id. rev-word.
data division.
Line 770 ⟶ 1,006:
.
end program rev-word.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 787 ⟶ 1,023:
=={{header|CoffeeScript}}==
{{trans|JavaScript}}
<langsyntaxhighlight lang="coffeescript">strReversed = '---------- Ice and Fire ------------\n\n
fire, in end will world the say Some\n
ice. in say Some\n
Line 798 ⟶ 1,034:
s.split('\n').map((l) -> l.split(/\s/).reverse().join ' ').join '\n'
 
console.log reverseString(strReversed)</langsyntaxhighlight>
{{out}}
As JavaScript.
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun split-and-reverse (str)
(labels
((iter (s lst)
Line 831 ⟶ 1,067:
(loop for line = (read-line s NIL)
while line
do (format t "~{~a~#[~:; ~]~}~%" (split-and-reverse line))))</langsyntaxhighlight>
 
Output is the same as everyone else's.
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.string, std.range, std.algorithm;
 
Line 853 ⟶ 1,089:
writefln("%(%-(%s %)\n%)",
text.splitLines.map!(r => r.split.retro));
}</langsyntaxhighlight>
The output is the same as the Python entry.
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">program RosettaCode_ReverseWordsInAString;
 
{$APPTYPE CONSOLE}
 
uses Classes, Types, StrUtils;
 
const
TXT =
'---------- Ice and Fire -----------'+sLineBreak+
sLineBreak+
'fire, in end will world the say Some'+sLineBreak+
'ice. in say Some'+sLineBreak+
'desire of tasted I''ve what From'+sLineBreak+
'fire. favor who those with hold I'+sLineBreak+
sLineBreak+
'... elided paragraph last ...'+sLineBreak+
sLineBreak+
'Frost Robert -----------------------'+sLineBreak;
 
var
i, w: Integer;
d: TStringDynArray;
begin
with TStringList.Create do
try
Text := TXT;
for i := 0 to Count - 1 do
begin
d := SplitString(Strings[i], #32);
Strings[i] := '';
for w := Length(d) - 1 downto 0 do
Strings[i] := Strings[i] + #32 + d[w];
end;
Writeln(Text);
finally
Free
end;
ReadLn;
end.</syntaxhighlight>
The output is the same as the Pascal entry.
 
=={{header|EasyLang}}==
<syntaxhighlight>
repeat
s$ = input
until error = 1
s$[] = strsplit s$ " "
for i = len s$[] downto 1
write s$[i] & " "
.
print ""
.
input_data
--------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------
</syntaxhighlight>
 
=={{header|EchoLisp}}==
Using a here-string input :
<langsyntaxhighlight lang="scheme">
(define S #<<
---------- Ice and Fire ------------
Line 875 ⟶ 1,176:
(for/list ((line (string-split S "\n")))
(string-join (reverse (string-split line " ")) " ")))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 891 ⟶ 1,192:
 
=={{header|Elena}}==
ELENA 6.x:
<lang elena>#import system.
<syntaxhighlight lang="elena">import extensions;
#import system'routines.
import system'routines;
 
#symbol program =
public program()
[
{
#var text := ("---------- Ice and Fire ------------",
var text := new string[]{"---------- Ice and Fire ------------",
"",
"fire, in end will world the say Some",
Line 905 ⟶ 1,207:
"... elided paragraph last ...",
"",
"Frost Robert -----------------------").};
text run &each.forEach: :(line )
[ {
line split &by:.splitBy(" " reverse run &each).sequenceReverse().forEach: :(word)
[{
console write:.print(word write:," ".)
].};
console writeLine.writeLine()
].}
}</syntaxhighlight>
].</lang>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule RC do
def reverse_words(txt) do
txt |> String.split("\n") # split lines
Line 927 ⟶ 1,229:
|> Enum.join("\n") # rejoin lines
end
end</langsyntaxhighlight>
Usage:
<langsyntaxhighlight lang="elixir">txt = """
---------- Ice and Fire ------------
Line 942 ⟶ 1,244:
"""
 
IO.puts RC.reverse_words(txt)</langsyntaxhighlight>
 
=={{header|Elm}}==
 
<syntaxhighlight lang="elm">
reversedPoem =
String.trim """
---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------
"""
 
reverseWords string =
string |> String.words |> List.reverse |> String.join " "
 
reverseLinesWords string =
string |> String.lines |> List.map reverseWords |> String.join "\n"
 
poem =
reverseLinesWords reversedPoem
</syntaxhighlight>
 
=={{header|Emacs Lisp}}==
 
<syntaxhighlight lang="lisp">(defun reverse-words (line)
<lang Emacs Lisp>
(defun reverse-words (line)
(insert
(format "%s\n"
Line 965 ⟶ 1,293:
"... elided paragraph last ..."
""
"Frost Robert ----------------------- "))</syntaxhighlight>
 
</lang>
{{out}}
'''Output''':
 
<pre>
------------ Fire and Ice ----------
Line 981 ⟶ 1,310:
</pre>
 
=={{header|ForthF_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
The method shown is based on submissions in comp.lang.forth. Comments have been added for those less familiar with reading Forth. This example makes use of the Forth interpreter/compiler internals by calling PARSE-NAME which is a Forth 2012 word that parses the input stream, ignores leading spaces and delimits at the space character. This method makes clever use of the data stack. Strings are not copied in memory by rather pointers are collected on the stack as PARSE-NAME processes a sentence. This of course leaves the strings in the reversed order so they are simply printed off the data stack.
//Reverse words in a string. Nigel Galloway: July 14th., 2021
<lang>create buf 1000 chars allot \ string buffer
[" ---------- Ice and Fire ------------ ";
buf value pp \ pp points to buffer address
" ";
" fire, in end will world the say Some ";
" ice. in say Some ";
" desire of tasted I've what From ";
" fire. favour who those with hold I ";
" ";
" ... elided paragraph last ... ";
" ";
" Frost Robert ----------------------- "]|>List.map(fun n->n.Split " "|>Array.filter((<>)"")|>Array.rev|>String.concat " ")|>List.iter(printfn "%s")
</syntaxhighlight>
{{out}}
<pre>
------------ Fire and Ice ----------
 
Some say the world will end in fire,
: tr ( caddr u -- )
Some say in ice.
dup >r pp swap cmove \ move string into buffer
From what I've tasted of desire
r> pp + to pp ; \ advance pointer by u bytes
I hold with those who favour fire.
 
... last paragraph elided ...
: collect ( -- addr len .. addr[n] len[n]) \ words deposit on data stack
begin
parse-name dup \ parse input stream, dup the len
while \ while stack <> 0
tuck pp >r tr r> swap
repeat
2drop ; \ clean up stack
 
----------------------- Robert Frost
: reverse ( -- )
</pre>
buf to pp \ initialize pointer to buffer address
=={{header|Factor}}==
collect
<syntaxhighlight lang="factor">USING: io sequences splitting ;
depth 2/ 0 ?do type space loop \ type the strings with a trailing space
IN: rosetta-code.reverse-words
cr ; \ final new line
 
"---------- Ice and Fire ------------
 
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
 
... elided paragraph last ...
 
Frost Robert -----------------------"
 
"\n" split [ " " split reverse " " join ] map [ print ] each</syntaxhighlight>
{{out}}
<pre>
------------ Fire and Ice ----------
 
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
 
... last paragraph elided ...
 
----------------------- Robert Frost
</pre>
 
=={{header|Forth}}==
The word "parse-name" consumes a word from input stream and places it on the stack. The word "type" takes a word from the data stack and prints it. Calling these two words before and after the recursive call effectively reverses a string.
<syntaxhighlight lang="text">: not-empty? dup 0 > ;
: (reverse) parse-name not-empty? IF recurse THEN type space ;
: reverse (reverse) cr ;
 
reverse ---------- Ice and Fire ------------
Line 1,013 ⟶ 1,382:
reverse ... elided paragraph last ...
reverse
reverse Frost Robert -----------------------</langsyntaxhighlight>
 
'''Output'''
Interpreted above code at the Forth console
<pre>
<pre>Some say the world will end in fire,
------------ Fire and Ice ----------
 
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
Line 1,031 ⟶ 1,403:
Fortran syntax is mostly Fortran 77.
 
<langsyntaxhighlight lang="fortran">
character*40 words
character*40 reversed
Line 1,060 ⟶ 1,432:
end
 
</syntaxhighlight>
</lang>
 
Output from comand: <b>cat frostPoem.txt | reverse</b><p>
Line 1,078 ⟶ 1,450:
Frost Robert ----------------------- => ----------------------- Robert Frost
 
</pre>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Sub split (s As String, sepList As String, result() As String, removeEmpty As Boolean = False)
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 - empty) = Mid(s, position(i - 1) + 1, length)
If removeEmpty Andalso CBool(length = 0) Then empty += 1
Next
 
If empty > 0 Then Redim Preserve result(count - empty)
End Sub
 
Dim s As String = "Hey you, Bub!"
Dim a() As String
split(s, " ", a(), true)
Dim reversed As String = ""
For i As Integer = UBound(a) To LBound(a) Step -1
reversed += a(i)
If i > LBound(a) Then reversed += " "
Next
 
Print "Original String = "; s
Print "Reversed String = "; reversed
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
 
{{out}}
<pre>
Original String = Hey you, Bub!
Reversed String = Bub! you, Hey
</pre>
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">
lines=split["\n",
"""---------- Ice and Fire ------------
Line 1,096 ⟶ 1,528:
for line = lines
println[join[" ", reverse[split[%r/\s+/, line]]]]
</syntaxhighlight>
</lang>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
CFStringRef frostStr
CFArrayRef frostArr, tempArr
CFMutableStringRef mutStr
NSInteger i, count
 
frostStr = @"---------- Ice and Fire ------------\n¬
\n¬
fire, in end will world the say Some\n¬
ice. in say Some\n¬
desire of tasted I've what From\n¬
fire. favor who those with hold I\n¬
\n¬
… elided paragraph last …\n¬
\n¬
Frost Robert -----------------------\n"
 
frostArr = fn StringComponentsSeparatedByString( frostStr, @"\n" )
count = fn ArrayCount( frostArr )
mutStr = fn MutableStringWithCapacity( 0 )
 
for i = 0 to count - 1
tempArr = fn StringComponentsSeparatedByString( frostArr[i], @" " )
tempArr = fn EnumeratorAllObjects( fn ArrayReverseObjectEnumerator( tempArr ) )
MutableStringAppendString( mutStr, fn ArrayComponentsJoinedByString( tempArr, @" " ) )
MutableStringAppendString( mutStr, @"\n" )
next
 
NSLog( @"%@", mutStr )
 
HandleEvents
</syntaxhighlight>
 
Output:
<pre>
------------ Fire and Ice ----------
 
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
 
… last paragraph elided …
 
----------------------- Robert Frost
</pre>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=c81c1bbf94e856035fd382015d208272 Click this link to run this code]'''
<syntaxhighlight lang="gambas">Public Sub Main()
Dim sString As New String[10] 'Array for the input text
Dim sLine As New String[] 'Array of each word in a line
Dim siCount0, siCount1 As Short 'Counters
Dim sOutput, sReverse, sTemp As String 'Strings
 
sString[0] = "---------- Ice And Fire ------------" 'Input text
sString[1] = " "
sString[2] = "fire, in end will world the say Some"
sString[3] = "ice. in say Some "
sString[4] = "desire of tasted I've what From "
sString[5] = "fire. favor who those with hold I "
sString[6] = " "
sString[7] = "... elided paragraph last ... "
sString[8] = " "
sString[9] = "Frost Robert -----------------------"
 
For siCount0 = 0 To 9 'To work through each line of input text
If Trim(sString[siCount0]) = "" Then sString[siCount0] = " " 'If the line is all spaces then make it 1 space
For Each sTemp In Split(Trim(sString[siCount0]), " ") 'Split the trimmed line by spaces
sLine.Add(sTemp) 'Add each word to the sLine array
Next
For siCount1 = sLine.max DownTo 0 'Loop from the last in the sLine array to 0
sReverse &= sLine[siCount1] & " " 'Fill sReverse with words reversed, adding a space
Next
sOutput &= Trim(sReverse) & gb.NewLine 'Add the reversed words to sOutput and add a newline
sReverse = "" 'Clear sReverse
sLine.Clear 'Clear sLine array
Next
 
Print sOutput 'Print the output
 
End</syntaxhighlight>
Output:
<pre>
------------ Fire And Ice ----------
 
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
 
... last paragraph elided ...
 
----------------------- Robert Frost
</pre>
 
=={{header|Gema}}==
<langsyntaxhighlight lang="gema">\L<G> <U>=@{$2} $1</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,137 ⟶ 1,671:
fmt.Println(t)
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,153 ⟶ 1,687:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def text = new StringBuilder()
.append('---------- Ice and Fire ------------\n')
.append(' \n')
Line 1,167 ⟶ 1,701:
text.eachLine { line ->
println "$line --> ${line.split(' ').reverse().join(' ')}"
}</langsyntaxhighlight>
{{output}}
<pre>---------- Ice and Fire ------------ --> ------------ Fire and Ice ----------
Line 1,181 ⟶ 1,715:
 
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">
<lang Haskell>
revstr :: String -> String
revstr = unwords . reverse . words -- point-free style
Line 1,200 ⟶ 1,734:
\\n\
\Frost Robert -----------------------\n" --multiline string notation requires \ at end and start of lines, and \n to be manually input
</syntaxhighlight>
</lang>
unwords, reverse, words, unlines, map and lines are built-in functions, all available at GHC's Prelude.
For better visualization, use "putStr test"
Line 1,207 ⟶ 1,741:
 
Works in both languages:
<langsyntaxhighlight lang="unicon">procedure main()
every write(rWords(&input))
end
Line 1,220 ⟶ 1,754:
procedure genWords()
while w := 1(tab(upto(" \t")),tab(many(" \t"))) || " " do suspend w
end</langsyntaxhighlight>
 
{{out}} for test file:
Line 1,237 ⟶ 1,771:
->
</pre>
 
=={{header|Insitux}}==
<syntaxhighlight lang="insitux">(var poem
"---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------")
 
(function split-join by then x
(-> x (split by) then (join by)))
 
(split-join "\n" (map @(split-join " " reverse)) poem)</syntaxhighlight>
 
=={{header|J}}==
Line 1,242 ⟶ 1,794:
Treated interactively:
 
<langsyntaxhighlight Jlang="j"> ([:;@|.[:<;.1 ' ',]);._2]0 :0
---------- Ice and Fire ------------
 
Line 1,264 ⟶ 1,816:
----------------------- Robert Frost
</syntaxhighlight>
</lang>
 
The verb phrase <code>( [: ; @ |. [: < ;. 1 ' ' , ])</code> reverses words in a string. The rest of the implementation has to do with defining the block of text we are working on, and applying this verb phrase to each line of that text.
 
Another approach:
 
<syntaxhighlight lang="j">echo ;:inv@|.@cut;._2 {{)n
---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------
}}</syntaxhighlight>
 
produces:
 
<pre>
------------ Fire and Ice ----------
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
... last paragraph elided ...
----------------------- Robert Frost
</pre>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public class ReverseWords {
 
static final String[] lines = {
Line 1,290 ⟶ 1,872:
}
}
}</langsyntaxhighlight>
{{works with|Java|8+}}
<langsyntaxhighlight lang="java">package string;
 
import static java.util.Arrays.stream;
Line 1,330 ⟶ 1,912:
;
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,346 ⟶ 1,928:
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">var strReversed =
"---------- Ice and Fire ------------\n\
\n\
Line 1,368 ⟶ 1,950:
console.log(
reverseString(strReversed)
);</langsyntaxhighlight>
 
Output:
Line 1,383 ⟶ 1,965:
 
=={{header|jq}}==
<langsyntaxhighlight lang="jq">split("[ \t\n\r]+") | reverse | join(" ")</langsyntaxhighlight>
This solution requires a version of jq with regex support for split.
 
The following example assumes the above line is in a file named reverse_words.jq and that the input text is in a file named IceAndFire.txt. The -r option instructs jq to read the input file as strings, line by line.<langsyntaxhighlight lang="sh">$ jq -R -r -M -f reverse_words.jq IceAndFire.txt
------------ Fire and Ice ----------
 
Line 1,396 ⟶ 1,978:
... last paragraph elided ...
 
----------------------- Robert Frost</langsyntaxhighlight>
 
=={{header|Jsish}}==
From Javascript entry.
<syntaxhighlight lang="javascript">var strReversed =
"---------- Ice and Fire ------------\n
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
\n... elided paragraph last ...\n
Frost Robert -----------------------";
function reverseString(s) {
return s.split('\n').map(
function (line) {
return line.split().reverse().join(' ');
}
).join('\n');
}
 
;reverseString('Hey you, Bub!');
;strReversed;
;reverseString(strReversed);
 
/*
=!EXPECTSTART!=
reverseString('Hey you, Bub!') ==> Bub! you, Hey
strReversed ==> ---------- Ice and Fire ------------
 
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
 
... elided paragraph last ...
 
Frost Robert -----------------------
reverseString(strReversed) ==> ------------ Fire and Ice ----------
 
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
 
... last paragraph elided ...
 
----------------------- Robert Frost
=!EXPECTEND!=
*/</syntaxhighlight>
 
{{out}}
<pre>
prompt$ jsish -u reverseWords.jsi
[PASS] reverseWords.jsi</pre>
 
=={{header|Julia}}==
<langsyntaxhighlight Julialang="julia">revstring (str) = join(reverse(split(str, " ")), " ")</langsyntaxhighlight>{{Out}}
<pre>julia> revstring("Hey you, Bub!")
"Bub! you, Hey"
Line 1,428 ⟶ 2,064:
----------------------- Robert Frost</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">fun reversedWords(s: String) = s.split(" ").filter { it.isNotEmpty() }.reversed().joinToString(" ")
 
fun main() {
val s = "Hey you, Bub!"
println(reversedWords(s))
println()
val sl = listOf(
" ---------- Ice and Fire ------------ ",
" ",
" fire, in end will world the say Some ",
" ice. in say Some ",
" desire of tasted I've what From ",
" fire. favor who those with hold I ",
" ",
" ... elided paragraph last ... ",
" ",
" Frost Robert ----------------------- ",
)
sl.forEach { println(reversedWords(it)) }
}</syntaxhighlight>
 
{{out}}
<pre>
Bub! you, Hey
 
------------ Fire and Ice ----------
 
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
 
... last paragraph elided ...
 
----------------------- Robert Frost
</pre>
 
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">
#!/bin/ksh
 
# Reverse words in a string
 
# # Variables:
#
typeset -a wArr
integer i
 
 
######
# main #
######
 
while read -A wArr; do
for ((i=${#wArr[@]}-1; i>=0; i--)); do
printf "%s " "${wArr[i]}"
done
echo
done << EOF
---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------
EOF</syntaxhighlight>
{{out}}<pre>
------------ Fire and Ice ----------
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
... last paragraph elided ...
----------------------- Robert Frost </pre>
 
=={{header|Lambdatalk}}==
This answer illustrates how a missing primitive (line_split) can be added directly in the wiki page.
<syntaxhighlight lang="scheme">
1) We write a function
 
{def line_reverse
{def line_reverse.r
{lambda {:i :txt :length}
{if {> :i :length}
then
else {br}{A2S {A.reverse! {A.get :i :txt}}}
{line_reverse.r {+ :i 1} :txt :length}}}}
{lambda {:txt}
{let { {:a {line_split {:txt}}} }
{line_reverse.r 0 :a {- {A.length :a} 1}}}} }
-> line_reverse
 
where A2S translates an array into a sentence
 
{def A2S
{lambda {:a}
{if {A.empty? :a}
then
else {A.first :a} {A2S {A.rest :a}}}}}
-> A2S
 
and line_split is a javascript primitive directly written in the wiki page,
added to the dictionary and returning an array of lines
 
LAMBDATALK.DICT['line_split'] = function () {
var args = arguments[0].split("\n");
var str = "{A.new ";
for (var i=0; i< args.length; i++)
str += "{A.new " + args[i] + "} ";
str += "}";
return LAMBDATALK.eval_forms( str )
};
 
2) input (from a simple text source without any presetting)
 
{def rosetta
---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I''ve what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------
}
-> rosetta
 
3) calling the function:
 
{line_reverse rosetta}
->
 
3) output
 
------------ Fire and Ice ----------
 
Some say the world will end in fire,
Some say in ice.
From what I''ve tasted of desire
I hold with those who favor fire.
 
... last paragraph elided ...
----------------------- Robert Frost
</syntaxhighlight>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
for i = 1 to 10
read string$
Line 1,457 ⟶ 2,247:
data ""
data "Frost Robert -----------------------"
</syntaxhighlight>
</lang>
{{Out}}
<pre>------------ Fire and Ice ----------
Line 1,472 ⟶ 2,262:
=={{header|LiveCode}}==
The input text has been entered into the contents of a text field called "Fieldtxt", add a button and put the following in its mouseUp
<langsyntaxhighlight LiveCodelang="livecode">repeat for each line txtln in fld "Fieldtxt"
repeat with i = the number of words of txtln down to 1
put word i of txtln & space after txtrev
Line 1,478 ⟶ 2,268:
put cr after txtrev -- preserve line
end repeat
put txtrev</langsyntaxhighlight>
 
 
=={{header|LiveScript}}==
<langsyntaxhighlight lang="livescript">
poem =
"""
Line 1,500 ⟶ 2,289:
reverse-string = (.split '\n') >> (.map reverse-words) >> (.join '\n')
reverse-string poem
</syntaxhighlight>
</lang>
 
=={{header|Logo}}==
This version just reads the words from standard input.
 
<langsyntaxhighlight lang="logo">do.until [
make "line readlist
print reverse :line
] [word? :line]
bye</langsyntaxhighlight>
 
{{Out}}
Line 1,535 ⟶ 2,324:
 
=={{header|Lua}}==
 
See below for original entry and the input string under variable 's'. Here is a significantly shorter program.
 
<syntaxhighlight lang="lua">
local lines = {}
for line in (s .. "\n"):gmatch("(.-)\n") do
local this = {}
for word in line:gmatch("%S+") do
table.insert(this, 1, word)
end
lines[#lines + 1] = table.concat(this, " ")
end
print(table.concat(lines, "\n"))
</syntaxhighlight>
 
 
 
Original response:
 
(''Note:'' The Wiki's syntax highlighting for Lua does not highlight the following valid string literal correctly, so the listing is split in two parts.)
Line 1,550 ⟶ 2,357:
]]
 
<langsyntaxhighlight lang="lua">function table.reverse(a)
local res = {}
for i = #a, 1, -1 do
Line 1,568 ⟶ 2,375:
for line, nl in s:gmatch("([^\n]-)(\n)") do
print(table.concat(table.reverse(splittokens(line)), ' '))
end</langsyntaxhighlight>
 
''Note:'' With the technique used here for splitting <code>s</code> into lines (not part of the task) the last line will be gobbled up if it does not end with a newline.
 
=={{header|MathematicaMaple}}==
<syntaxhighlight lang="maple">while (true) do
<lang Mathematica>poem = "---------- Ice and Fire ------------
input := readline("input.txt"):
if input = 0 then break: fi:
input := StringTools:-Trim(input): # remove leading/trailing space
input := StringTools:-Join(ListTools:-Reverse(StringTools:-Split(input, " "))," "):
printf("%s\n", input):
od:</syntaxhighlight>
{{Out|Output}}
<pre>------------ Fire and Ice ----------
 
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
 
... last paragraph elided ...
 
----------------------- Robert Frost</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">poem = "---------- Ice and Fire ------------
fire, in end will world the say Some
Line 1,588 ⟶ 2,415:
linesWithReversedWords =
StringJoin[Riffle[#, " "]] & /@ reversedWordArray;
finaloutput = StringJoin[Riffle[#, "\n"]] & @ linesWithReversedWords</langsyntaxhighlight>
{{out}}
<pre>------------ Fire and Ice ----------
Line 1,601 ⟶ 2,428:
----------------------- Robert Frost</pre>
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight MATLABlang="matlab">function testReverseWords
testStr = {'---------- Ice and Fire ------------' ; ...
'' ; ...
Line 1,626 ⟶ 2,453:
strOut = strtrim(sprintf('%s ', words{end:-1:1}));
end
end</langsyntaxhighlight>
{{out}}
<pre>------------ Fire and Ice ----------
Line 1,638 ⟶ 2,465:
 
----------------------- Robert Frost</pre>
 
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">
-- MAXScript : Reverse words in a string : N.H. 2019
--
(
text = stringstream "---------- Ice and Fire ------------\n\nfire, in end will world the say Some\nice. in say Some\ndesire of tasted I've what From\nfire. favor who those with hold I\n\n... elided paragraph last ...\n\nFrost Robert -----------------------\n"
clearListener()
seek text 0
while eof text == false do
(
nextLine = (readLine text)
if nextLine == "" then
(
print ""
continue
) -- end of if
revLine = ""
eachWord = filterString nextLine " "
for k = eachWord.count to 1 by -1 do
(
revLine = revLine + eachWord[k]
-- Only add space between words not at the end of line
if k != 1 then revLine = revLine + " "
) -- end of for k
print revLine
) -- end of while eof
)
</syntaxhighlight>
{{out}}
Output to MAXScript Listener:
<pre>"------------ Fire and Ice ----------"
""
"Some say the world will end in fire,"
"Some say in ice."
"From what I've tasted of desire"
"I hold with those who favor fire."
""
"... last paragraph elided ..."
""
"----------------------- Robert Frost"</pre>
 
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">lines = ["==========================================",
"| ---------- Ice and Fire ------------ |",
"| |",
"| fire, in end will world the say Some |",
"| ice. in say Some |",
"| desire of tasted I've what From |",
"| fire. favor who those with hold I |",
"| |",
"| ... elided paragraph last ... |",
"| |",
"| Frost Robert ----------------------- |",
"=========================================="]
for line in lines
oldLine = line.split
newLine = []
while oldLine
// the line below line retains the outer box format
newLine.push oldLine.pop
// alternate format, replace above line with below two lines below to strip all superfluous spaces
// word = oldLine.pop
// if word != "" then newLine.push word
end while
print newLine.join
end for</syntaxhighlight>
{{out}}
<pre>
==========================================
| ------------ Fire and Ice ---------- |
| |
| Some say the world will end in fire, |
| Some say in ice. |
| From what I've tasted of desire |
| I hold with those who favor fire. |
| |
| ... last paragraph elided ... |
| |
| ----------------------- Robert Frost |
==========================================
</pre>
 
=={{header|Modula-2}}==
{{trans|Pascal}}
{{works with|ADW Modula-2|any (Compile with the linker option ''Console Application'').}}
<syntaxhighlight lang="modula2">
MODULE ReverseWords;
 
FROM STextIO IMPORT
WriteString, WriteLn;
FROM Strings IMPORT
Assign, Concat, Append;
 
CONST
NL = CHR(10);
Sp = ' ';
Txt = "---------- Ice and Fire -----------" + NL +
NL +
"fire, in end will world the say Some" + NL +
"ice. in say Some" + NL +
"desire of tasted I've what From" + NL +
"fire. favor who those with hold I" + NL +
NL +
"... elided paragraph last ..." + NL +
NL +
"Frost Robert -----------------------" + NL;
 
TYPE
String400 = ARRAY [0 .. 399] OF CHAR;
 
PROCEDURE AddWord(Source: ARRAY OF CHAR; VAR INOUT Destination: ARRAY OF CHAR);
VAR
R: String400;
BEGIN
Concat(Source, Sp, R);
Append(Destination, R);
Assign(R, Destination);
END AddWord;
 
VAR
I: CARDINAL;
SingleWord, CurrentLine: String400;
C: CHAR;
 
BEGIN
SingleWord := "";
CurrentLine := "";
FOR I := 0 TO HIGH(Txt) DO
C := Txt[I];
CASE C OF
Sp:
AddWord(SingleWord, CurrentLine);
SingleWord := ""; |
NL:
AddWord(SingleWord, CurrentLine);
WriteString(CurrentLine);
WriteLn;
SingleWord := "";
CurrentLine := ""; |
ELSE
Append(C, SingleWord);
END;
END;
END ReverseWords.
</syntaxhighlight>
 
=={{header|Nanoquery}}==
<syntaxhighlight lang="nanoquery">def reverse_words(string)
tokens = split(string, " ")
if len(tokens) = 0
return ""
end
 
ret_str = ""
for i in range(len(tokens) - 1, 0)
ret_str += tokens[i] + " "
end
return ret_str.substring(0, len(ret_str) - 1)
end
 
data = "---------- Ice and Fire ------------\n" +\
" \n" +\
"fire, in end will world the say Some\n" +\
"ice. in say Some \n" +\
"desire of tasted I've what From \n" +\
"fire. favor who those with hold I \n" +\
" \n" +\
"... elided paragraph last ... \n" +\
"Frost Robert -----------------------\n"
 
for line in split(data, "\n")
println reverse_words(line)
end</syntaxhighlight>
{{out}}
<pre>------------ Fire and Ice ----------
 
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
 
... last paragraph elided ...
----------------------- Robert Frost</pre>
 
=={{header|Nial}}==
 
{{works with|Q'Nial Version 6.3}}
 
<syntaxhighlight lang="nial">
# Define a function to convert a list of strings to a single string.
join is rest link (' ' eachboth link)
 
iterate (write join reverse (' ' string_split)) \
\
\
'------------ Eldorado ----------' \
'' \
'... here omitted lines ...' \
'' \
'Mountains the "Over' \
'Moon, the Of' \
'Shadow, the of Valley the Down' \
'ride," boldly Ride,' \
'replied,--- shade The' \
'Eldorado!" for seek you "If' \
'' \
'Poe Edgar -----------------------'
</syntaxhighlight>
 
{{out}}
<pre>
---------- Eldorado ------------
 
... lines omitted here ...
 
"Over the Mountains
Of the Moon,
Down the Valley of the Shadow,
Ride, boldly ride,"
The shade replied,---
"If you seek for Eldorado!"
 
----------------------- Edgar Poe
</pre>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import strutils
 
let text = """---------- Ice and Fire ------------
Line 1,666 ⟶ 2,719:
 
for line in text.splitLines():
echo line.split(' ').reversed().join(" ")</langsyntaxhighlight>
{{out}}
<pre>------------ Fire and Ice ----------
Line 1,680 ⟶ 2,733:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">use Collection;
 
class Reverselines {
Line 1,708 ⟶ 2,761:
};
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,723 ⟶ 2,776:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">#load "str.cma"
let input = ["---------- Ice and Fire ------------";
"";
Line 1,738 ⟶ 2,791:
let reversed = List.map List.rev splitted in
let final = List.map (String.concat " ") reversed in
List.iter print_endline final;;</langsyntaxhighlight>
Sample usage
<pre>$ ocaml reverse.ml
Line 1,755 ⟶ 2,808:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: revWords(s)
s words reverse unwords ;
 
Line 1,768 ⟶ 2,821:
"... elided paragraph last ... " revWords println
" " revWords println
"Frost Robert -----------------------" revWords println ;</langsyntaxhighlight>
 
{{out}}
Line 1,785 ⟶ 2,838:
ok
</pre>
 
=={{header|Pascal}}==
Free Pascal 3.0.0
<syntaxhighlight lang="pascal">program Reverse_words(Output);
{$H+}
 
const
nl = chr(10); // Linefeed
sp = chr(32); // Space
TXT =
'---------- Ice and Fire -----------'+nl+
nl+
'fire, in end will world the say Some'+nl+
'ice. in say Some'+nl+
'desire of tasted I''ve what From'+nl+
'fire. favor who those with hold I'+nl+
nl+
'... elided paragraph last ...'+nl+
nl+
'Frost Robert -----------------------'+nl;
 
var
I : integer;
ew, lw : ansistring;
c : char;
 
function addW : ansistring;
var r : ansistring = '';
begin
r := ew + sp + lw;
ew := '';
addW := r
end;
 
begin
ew := '';
lw := '';
 
for I := 1 to strlen(TXT) do
begin
c := TXT[I];
case c of
sp : lw := addW;
nl : begin writeln(addW); lw := '' end;
else ew := ew + c
end;
end;
readln;
end.</syntaxhighlight>
{{out}}
<pre>----------- Fire and Ice ----------
 
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
 
... last paragraph elided ...
 
----------------------- Robert Frost</pre>
 
Another version (tested with FPC 3.2.2)
<syntaxhighlight lang="pascal">
program reverse_words;
{$mode objfpc}{$h+}
uses
SysUtils;
 
function Reverse(a: TStringArray): TStringArray;
var
I, J: SizeInt;
t: Pointer;
begin
I := 0;
J := High(a);
while I < J do begin
t := Pointer(a[I]);
Pointer(a[I]) := Pointer(a[J]);
Pointer(a[J]) := t;
Inc(I);
Dec(J);
end;
Result := a;
end;
 
const
Input =
'---------- Ice and Fire -----------' + LineEnding +
'' + LineEnding +
'fire, in end will world the say Some' + LineEnding +
'ice. in say Some' + LineEnding +
'desire of tasted I''ve what From' + LineEnding +
'fire. favor who those with hold I' + LineEnding +
'' + LineEnding +
'... elided paragraph last ...' + LineEnding +
'' + LineEnding +
'Frost Robert -----------------------' + LineEnding;
var
Line: string;
 
begin
for Line in Input.Split([LineEnding], TStringSplitOptions.ExcludeLastEmpty) do
WriteLn(string.Join(' ', Reverse(Line.Split([' ']))));
end.
</syntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">print join(" ", reverse split), "\n" for <DATA>;
__DATA__
---------- Ice and Fire ------------
Line 1,799 ⟶ 2,957:
Frost Robert -----------------------
</syntaxhighlight>
</lang>
 
=={{header|Perl 6Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
We'll read input from stdin
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<lang perl6>say ~.words.reverse for lines</lang>
<span style="color: #008080;">constant</span> <span style="color: #000000;">test</span><span style="color: #0000FF;">=</span><span style="color: #008000;">"""
---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------
"""</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">lines</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: #008000;">'\n'</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">lines</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</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;">lines</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">))</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
<pre>------------ Fire and Ice ----------
------------ Fire and Ice ----------
 
Some say the world will end in fire,
Line 1,814 ⟶ 2,991:
... last paragraph elided ...
 
----------------------- Robert Frost</pre>
</pre>
 
=={{header|Phixmonti}}==
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt
 
"---------- Ice and Fire ------------"
""
"fire, in end will world the say Some"
"ice. in say Some"
"desire of tasted I've what From"
"fire. favor who those with hold I"
""
"... elided paragraph last ..."
""
"Frost Robert -----------------------"
 
stklen tolist
len for var i
i get split reverse i set
endfor
len for
get len dup if
for get print " " print endfor
else drop endif
drop nl
endfor</syntaxhighlight>
{{out}}
<pre>
------------ Fire and Ice ----------
 
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
 
... last paragraph elided ...
 
----------------------- Robert Frost
</pre>
 
=={{header|PHP}}==
<syntaxhighlight lang="php">
<?php
function strInv ($string) {
 
$str_inv = '' ;
 
for ($i=0,$s=count($string);$i<$s;$i++){
$str_inv .= implode(' ',array_reverse(explode(' ',$string[$i])));
$str_inv .= '<br>';
}
 
return $str_inv;
 
}
$string[] = "---------- Ice and Fire ------------";
$string[] = "";
$string[] = "fire, in end will world the say Some";
$string[] = "ice. in say Some";
$string[] = "desire of tasted I've what From";
$string[] = "fire. favor who those with hold I";
$string[] = "";
$string[] = "... elided paragraph last ...";
$string[] = "";
$string[] = "Frost Robert ----------------------- ";
 
 
echo strInv($string);</syntaxhighlight>
'''Output''':
 
<syntaxhighlight lang="shell">------------ Fire and Ice ----------
 
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
 
... last paragraph elided ...
 
----------------------- Robert Frost</syntaxhighlight>
 
=={{header|PicoLisp}}==
<syntaxhighlight lang="picolisp">
<lang PicoLisp>
(in "FireIce.txt"
(until (eof)
(prinl (glue " " (flip (split (line) " "))))))
</syntaxhighlight>
</lang>
{{Out}}
Same as anybody else.
 
=={{header|Pike}}==
<syntaxhighlight lang="pike">string story = #"---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------";
 
foreach(story/"\n", string line)
write("%s\n", reverse(line/" ")*" ");
</syntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">rev: procedure options (main); /* 5 May 2014 */
declare (s, reverse) character (50) varying;
declare (i, j) fixed binary;
Line 1,857 ⟶ 3,133:
put edit ('---> ', reverse) (col(40), 2 A);
end;
end rev;</langsyntaxhighlight>
{{out}}
<pre>
Line 1,874 ⟶ 3,150:
=={{header|PowerShell}}==
{{works with|PowerShell|4.0}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
Function Reverse-Words($lines) {
$lines | foreach {
Line 1,895 ⟶ 3,171:
 
Reverse-Words($lines)
</syntaxhighlight>
</lang>
 
'''output''' :
Line 1,912 ⟶ 3,188:
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang="purebasic">a$ = "---------- Ice and Fire ------------" +#CRLF$+
" " +#CRLF$+
"fire, in end will world the say Some" +#CRLF$+
Line 1,933 ⟶ 3,209:
Next
Input()
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,951 ⟶ 3,227:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python"> text = '''\
---------- Ice and Fire ------------
 
Line 1,963 ⟶ 3,239:
Frost Robert -----------------------'''
 
for line in text.split('\n'): print(' '.join(line.split()[::-1]))</langsyntaxhighlight>
 
'''Output''':
 
<langsyntaxhighlight Shelllang="shell">------------ Fire and Ice ----------
 
Some say the world will end in fire,
Line 1,976 ⟶ 3,252:
... last paragraph elided ...
 
----------------------- Robert Frost</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> ' [ $ " ---------- Ice and Fire ------------ "
$ ""
$ " fire, in end will world the say Some "
$ " ice. in say Some "
$ " desire of tasted I've what From "
$ " fire. favor who those with hold I "
$ ""
$ " ... elided paragraph last ... "
$ ""
$ " Frost Robert ----------------------- " ]
witheach
[ do nest$ reverse
witheach
[ echo$ sp ]
cr ]</syntaxhighlight>
 
{{out}}
 
<pre>------------ Fire and Ice ----------
 
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
 
... last paragraph elided ...
 
----------------------- Robert Frost </pre>
 
=={{header|R}}==
 
<syntaxhighlight lang="r">
whack <- function(s) {
paste( rev( unlist(strsplit(s, " "))), collapse=' ' ) }
 
poem <- unlist( strsplit(
'------------ Eldorado ----------
 
... here omitted lines ...
 
Mountains the "Over
Moon, the Of
Shadow, the of Valley the Down
ride," boldly Ride,
replied,--- shade The
Eldorado!" for seek you "If
 
Poe Edgar -----------------------', "\n"))
 
for (line in poem) cat( whack(line), "\n" )
</syntaxhighlight>
 
{{out}}
<pre>
---------- Eldorado ------------
 
... lines omitted here ...
 
"Over the Mountains
Of the Moon,
Down the Valley of the Shadow,
Ride, boldly ride,"
The shade replied,---
"If you seek for Eldorado!"
 
----------------------- Edgar Poe
</pre>
 
As a dangerous stunt, let's redefine "<tt>{</tt>".
(Everything that happens in R is a function-call.)
 
<syntaxhighlight lang="r">
> `{` <- function(s) rev(unlist(strsplit(s, " ")))
> {"one two three four five"}
[1] "five" "four" "three" "two" "one"
</syntaxhighlight>
 
You had better restart your REPL after trying this.
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket/base
 
(require racket/string)
Line 2,006 ⟶ 3,364:
(begin (displayln (split-reverse l))
(loop (read-line poem-port))))))
</syntaxhighlight>
</lang>
 
In Wheeler-readable/sweet notation (https://readable.sourceforge.io/) as implemented by Asumu Takikawa (https://github.com/takikawa/sweet-racket):
<syntaxhighlight lang="racket">
#lang sweet-exp racket/base
require racket/string
 
define split-reverse(str)
string-join $ reverse $ string-split str
 
define poem
"---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------"
let
\\
poem-port $ open-input-string poem
let loop
\\
l $ read-line poem-port
unless eof-object?(l)
begin
displayln split-reverse(l)
loop read-line(poem-port)
</syntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
We'll read input from stdin
<syntaxhighlight lang="raku" line>say ~.words.reverse for lines</syntaxhighlight>
{{out}}
<pre>------------ Fire and Ice ----------
 
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
 
... last paragraph elided ...
 
----------------------- Robert Frost</pre>
 
=={{header|Red}}==
<syntaxhighlight lang="red">Red []
foreach line
split
{---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------} newline [
print reverse split line " "
]
</syntaxhighlight>
 
=={{header|REXX}}==
===natural order===
This REXX version process the words in a natural order (first to last).
<langsyntaxhighlight lang="rexx">/*REXX program reverses the order of tokens in a string (but not the letters).*/
@.=; @.1 = "---------- Ice and Fire ------------"
@.2 = ' '
Line 2,030 ⟶ 3,454:
 
say $ /*display the newly constructed line. */
end /*j*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
'''output''' &nbsp; when using the (internal text) ten lines of input:
<pre>
Line 2,047 ⟶ 3,471:
===reverse order===
This REXX version process the words in reverse order (last to first).
<langsyntaxhighlight lang="rexx">/*REXX program reverses the order of tokens in a string (but not the letters).*/
@.=; @.1 = "---------- Ice and Fire ------------"
@.2 = ' '
Line 2,066 ⟶ 3,490:
 
say $ /*display the newly constructed line. */
end /*j*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
'''output''' &nbsp; is the same as the 1<sup>st</sup> REXX version. <br><br>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
aList = str2list("
---------- Ice and Fire ------------
Line 2,088 ⟶ 3,512:
for y in aList2 see y + " " next see nl
next
</syntaxhighlight>
</lang>
 
Output
<langsyntaxhighlight lang="ring">
------------ Fire and Ice ----------
 
Line 2,101 ⟶ 3,525:
... last paragraph elided ...
----------------------- Robert Frost
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
« { }
'''WHILE''' OVER " " POS '''REPEAT'''
LASTARG → sep
« OVER 1 sep SUB +
SWAP sep 1 + OVER SIZE SUB SWAP
»
'''END'''
SWAP + REVLIST
'''IFERR''' ∑LIST '''THEN''' 1 GET '''END'''
» '<span style="color:blue">REVWORDS</span>' STO
{ "---------- Ice and Fire ------------" "" "fire, in end will world the say Some" "ice. in say Some" "desire of tasted I've what From" "fire. favor who those with hold I" "" "... elided paragraph last ..." "" "Frost Robert -----------------------" }
1 « <span style="color:blue">REVWORDS</span> » DOLIST
 
{{out}}
<pre>
1: { "------------ Fire and Ice ----------"
""
"Some say the world will end in fire,"
"Some say in ice."
"From what I've tasted of desire"
"I hold with those who favor fire."
""
"... last paragraph elided ..."
""
"----------------------- Robert Frost" }
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">puts <<EOS
---------- Ice and Fire ------------
 
Line 2,116 ⟶ 3,569:
Frost Robert -----------------------
EOS
.each_line.map {|line| line.split.reverse.join(' ')}</langsyntaxhighlight>
 
Output the same as everyone else's.
 
=={{header|Run BASIC}}==
<syntaxhighlight lang="runbasic">for i = 1 to 10
read string$
j = 1
r$ = ""
while word$(string$,j) <> ""
r$ = word$(string$,j) + " " + r$
j = j + 1
WEND
print r$
next
end
data "---------- Ice and Fire ------------"
data ""
data "fire, in end will world the say Some"
data "ice. in say Some"
data "desire of tasted I've what From"
data "fire. favor who those with hold I"
data ""
data "... elided paragraph last ..."
data ""
data "Frost Robert -----------------------"</syntaxhighlight>
Output:
<pre>------------ Fire and Ice ----------
 
Some say the world will end in fire,
Some say in ice.
From what I''ve tasted of desire
I hold with those who favor fire.
 
... last paragraph elided ...
 
----------------------- Robert Frost </pre>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">const TEXT: &'static str =
"---------- Ice and Fire ------------
Line 2,143 ⟶ 3,631:
.collect::<Vec<_>>() // Collect lines into Vec<String>
.join("\n")); // Concatenate lines into String
}</langsyntaxhighlight>
 
=={{header|S-lang}}==
<syntaxhighlight lang="s-lang">variable ln, in =
["---------- Ice and Fire ------------",
"fire, in end will world the say Some",
"ice. in say Some",
"desire of tasted I've what From",
"fire. favor who those with hold I",
"",
"... elided paragraph last ...",
"",
"Frost Robert -----------------------"];
 
foreach ln (in) {
ln = strtok(ln, " \t");
array_reverse(ln);
() = printf("%s\n", strjoin(ln, " "));
}</syntaxhighlight>
{{out}}
<pre>------------ Fire and Ice ----------
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
 
... last paragraph elided ...
 
----------------------- Robert Frost</pre>
 
=={{header|Scala}}==
{{works with|Scala|2.9.x}}
 
<langsyntaxhighlight Scalalang="scala">object ReverseWords extends App {
 
"""| ---------- Ice and Fire ------------
Line 2,164 ⟶ 3,680:
.foreach{println}
}</langsyntaxhighlight>
 
{{out}}
Line 2,183 ⟶ 3,699:
{{works with|Gauche Scheme}}
 
<syntaxhighlight lang="scheme">
<lang Scheme>
(for-each
(lambda (s) (print (string-join (reverse (string-split s #/ +/)))))
Line 2,198 ⟶ 3,714:
Frost Robert -----------------------"
#/[ \r]*\n[ \r]*/))
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 2,212 ⟶ 3,728:
----------------------- Robert Frost
</pre>
 
=={{header|sed}}==
<syntaxhighlight lang="sed">#!/usr/bin/sed -f
 
G
:loop
s/^[[:space:]]*\([^[:space:]][^[:space:]]*\)\(.*\n\)/\2 \1/
t loop
s/^[[:space:]]*//</syntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const array string: lines is [] (
Line 2,241 ⟶ 3,766:
writeln;
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,255 ⟶ 3,780:
----------------------- Robert Frost
</pre>
 
=={{header|SenseTalk}}==
<syntaxhighlight lang="sensetalk">set poem to {{
---------- Ice and Fire ------------
 
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
 
... elided paragraph last ...
 
Frost Robert -----------------------
}}
 
repeat with each line in poem
put (each word of it) reversed joined by space
end repeat
</syntaxhighlight>
{{out}}
<pre>
------------ Fire and Ice ----------
 
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
 
... last paragraph elided ...
 
----------------------- Robert Frost
</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">DATA.each{|line| line.words.reverse.join(" ").say};
 
__DATA__
Line 2,270 ⟶ 3,827:
... elided paragraph last ...
 
Frost Robert -----------------------</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="smalltalk">
poem := '---------- Ice and Fire ------------
Line 2,286 ⟶ 3,843:
 
(poem lines collect: [ :line | ((line splitOn: ' ') reverse) joinUsing: ' ' ]) joinUsing: (String cr).
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,306 ⟶ 3,863:
This only considers space as the word separator, not tabs, form feeds or any other sort of whitespace. (This, however, turns out not to be an issue with the example input.)
 
<langsyntaxhighlight lang="sparkling">let lines = split("---------- Ice and Fire ------------
 
fire, in end will world the say Some
Line 2,325 ⟶ 3,882:
 
print();
});</langsyntaxhighlight>
 
=={{header|Standard ML}}==
<syntaxhighlight lang="sml">val lines = [
" ---------- Ice and Fire ------------ ",
" ",
" fire, in end will world the say Some ",
" ice. in say Some ",
" desire of tasted I've what From ",
" fire. favor who those with hold I ",
" ",
" ... elided paragraph last ... ",
" ",
" Frost Robert ----------------------- "
]
 
val revWords = String.concatWith " " o rev o String.tokens Char.isSpace
 
val () = app (fn line => print (revWords line ^ "\n")) lines</syntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">import Foundation
 
// convenience extension for better clarity
Line 2,348 ⟶ 3,923:
let output = input.lines.map { $0.words.reverse().joinWithSeparator(" ") }.joinWithSeparator("\n")
 
print(output)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,362 ⟶ 3,937:
----------------------- Robert Frost
</pre>
 
=={{header|Tailspin}}==
<syntaxhighlight lang="tailspin">
def input: ['---------- Ice and Fire ------------',
'',
'fire, in end will world the say Some',
'ice. in say Some',
'desire of tasted I''ve what From',
'fire. favor who those with hold I',
'',
'... elided paragraph last ...',
'',
'Frost Robert -----------------------']
;
composer words
[ <word>* ]
rule word: <~WS> <WS>?
end words
$input... -> '$ -> words -> $(last..first:-1)...;
' -> !OUT::write
</syntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">set lines {
"---------- Ice and Fire ------------"
""
Line 2,380 ⟶ 3,978:
# This would also work for data this simple:
### puts [lreverse $line]
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,396 ⟶ 3,994:
Alternatively…
{{works with|Tcl|8.6}}
<langsyntaxhighlight lang="tcl">puts [join [lmap line $lines {lreverse $line}] "\n"]</langsyntaxhighlight>
 
=={{header|TXR}}==
Run from command line:
<syntaxhighlight lang ="bash">txr reverse.txr verse.txt</langsyntaxhighlight>
'''Solution:'''
<langsyntaxhighlight lang="txr">@(collect)
@ (some)
@(coll)@{words /[^ ]+/}@(end)
Line 2,415 ⟶ 4,013:
@ (end)
@(end)
</syntaxhighlight>
</lang>
New line should be present after the last @(end) terminating vertical definition.
i.e.
<langsyntaxhighlight lang="txr">@(end)
[EOF]</langsyntaxhighlight>
not
<syntaxhighlight lang ="txr">@(end)[EOF]</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
{{works with|bash}}
<langsyntaxhighlight lang="bash">while read -a words; do
for ((i=${#words[@]}-1; i>=0; i--)); do
printf "%s " "${words[i]}"
Line 2,441 ⟶ 4,039:
 
Frost Robert -----------------------
END</langsyntaxhighlight>
{{works with|ksh}}
Same as above, except change <langsyntaxhighlight lang="bash">read -a</langsyntaxhighlight> to <syntaxhighlight lang ="bash">read -A</langsyntaxhighlight>
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">
Option Explicit
 
Sub Main()
Dim Lines(9) As String, i&
'Input
Lines(0) = "------------- Ice And Fire -------------"
Lines(1) = ""
Lines(2) = "fire, in end will world the say Some"
Lines(3) = "ice. in say Some"
Lines(4) = "desire of tasted I've what From"
Lines(5) = "fire. favor who those with hold I"
Lines(6) = ""
Lines(7) = "... elided paragraph last ..."
Lines(8) = ""
Lines(9) = "Frost Robert -----------------------"
'Output
For i = 0 To 9
Debug.Print ReverseLine(Lines(i), " ")
Next
End Sub
 
Private Function ReverseLine(Line As String, Optional Separat As String) As String
Dim T, R, i&, j&, deb&, fin&
If Len(Line) = 0 Then
ReverseLine = vbNullString
Else
If Separat = "" Then Separat = " "
T = Split(Line, Separat)
ReDim R(UBound(T)): j = LBound(T)
deb = UBound(T): fin = deb / 2
For i = deb To fin Step -1
R(j) = T(i)
R(i) = T(j)
j = j + 1
Next i
ReverseLine = Join(R, Separat)
End If
End Function</syntaxhighlight>
{{Out}}
<pre>------------- Fire And Ice -------------
 
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
 
... last paragraph elided ...
 
----------------------- Robert Frost</pre>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
 
Line 2,486 ⟶ 4,136:
objOutFile.Close
Set objFSO = Nothing
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,502 ⟶ 4,152:
----------------------- Robert Frost
</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">fn main() {
mut n := [
"---------- Ice and Fire ------------",
" ",
"fire, in end will world the say Some",
"ice. in say Some ",
"desire of tasted I've what From ",
"fire. favor who those with hold I ",
" ",
"... elided paragraph last ... ",
" ",
"Frost Robert -----------------------",
]
for i, s in n {
mut t := s.fields() // tokenize
// reverse
last := t.len - 1
for j, k in t[..t.len/2] {
t[j], t[last-j] = t[last-j], k
}
n[i] = t.join(" ")
}
// display result
for t in n {
println(t)
}
}</syntaxhighlight>
 
 
'''Simpler version:'''
<syntaxhighlight lang="vlang">mut n := [
"---------- Ice and Fire ------------",
" ",
"fire, in end will world the say Some",
"ice. in say Some ",
"desire of tasted I've what From ",
"fire. favor who those with hold I ",
" ",
"... elided paragraph last ... ",
" ",
"Frost Robert -----------------------",
]
 
println(
n.map(
it.fields().reverse().join(' ').trim_space()
).join('\n')
)</syntaxhighlight>
 
 
{{out}}
<pre>
------------ Fire and Ice ----------
 
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
 
... last paragraph elided ...
 
----------------------- Robert Frost
</pre>
 
=={{header|Wren}}==
<syntaxhighlight lang="wren">var lines = [
"---------- Ice and Fire ------------",
" ",
"fire, in end will world the say Some",
"ice. in say Some ",
"desire of tasted I've what From ",
"fire. favor who those with hold I ",
" ",
"... elided paragraph last ... ",
" ",
"Frost Robert -----------------------"
]
 
for (line in lines) {
var tokens = line.trim().split(" ")
tokens = tokens[-1..0]
System.print(tokens.join(" "))
}</syntaxhighlight>
 
{{out}}
<pre>
------------ Fire and Ice ----------
 
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
 
... last paragraph elided ...
 
----------------------- Robert Frost
</pre>
 
=={{header|XBS}}==
<syntaxhighlight lang="xbs">func revWords(x:string=""){
(x=="")&=>send x+"<br>";
set sp = x::split(" ");
send sp::reverse()::join(" ");
}
set lines:array=[
"---------- Ice and Fire ------------",
"",
"fire, in end will world the say Some",
"ice. in say Some",
"desire of tasted I've what From",
"fire. favor who those with hold I",
"",
"... elided paragraph last ...",
"",
"Frost Robert -----------------------",
];
foreach(v of lines){
log(revWords(v));
}</syntaxhighlight>
{{out}}
<pre>
------------ Fire and Ice ----------
 
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
 
... last paragraph elided ...
 
----------------------- Robert Frost
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">string 0;
def LF=$0A, CR=$0D;
 
proc Reverse(Str, Len); \Reverse order of chars in string
char Str; int Len;
int I, J, T;
[I:= 0;
J:= Len-1;
while I < J do
[T:= Str(I); Str(I):= Str(J); Str(J):= T;
I:= I+1; J:= J-1;
];
];
 
char Str;
int I, LineBase, WordBase;
[Str:=
"---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------";
I:= 0;
repeat LineBase:= I;
loop [WordBase:= I;
repeat I:= I+1 until Str(I) <= $20;
Reverse(@Str(WordBase), I-WordBase);
if Str(I)=CR or Str(I)=LF or Str(I)=0 then quit;
I:= I+1; \skip space
];
Reverse(@Str(LineBase), I-LineBase);
while Str(I)=CR or Str(I)=LF do I:= I+1;
until Str(I) = 0;
Text(0, Str);
CrLf(0);
]</syntaxhighlight>
 
{{out}}
<pre>
------------ Fire and Ice ----------
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
... last paragraph elided ...
----------------------- Robert Frost
</pre>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">data " ---------- Ice and Fire ------------ "
data " "
data " fire, in end will world the say Some "
data " ice. in say Some "
data " desire of tasted I've what From "
data " fire. favor who those with hold I "
data " "
data " ... elided paragraph last ... "
data " "
data " Frost Robert ----------------------- "
data ""
 
dim w$(1)
 
do
read l$
if l$ <> "" then
n = token(l$, w$(), " ")
for i = n to 1 step -1
print w$(i), " ";
next
print
else
break
end if
loop</syntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">text:=Data(0,String,
#<<<
"---------- Ice and Fire ------------
Line 2,520 ⟶ 4,391:
text.pump(11,Data,fcn(s){ // process stripped lines
s.split(" ").reverse().concat(" ") + "\n" })
.text.print();</langsyntaxhighlight>
{{out}}
<pre>
1,995

edits