Reverse words in a string: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 45: Line 45:
{{trans|Python}}
{{trans|Python}}


<lang 11l>V text =
<syntaxhighlight lang="11l">V text =
‘---------- Ice and Fire ------------
‘---------- Ice and Fire ------------


Line 58: Line 58:


L(line) text.split("\n")
L(line) text.split("\n")
print(reversed(line.split(‘ ’)).join(‘ ’))</lang>
print(reversed(line.split(‘ ’)).join(‘ ’))</syntaxhighlight>


{{out}}
{{out}}
Line 75: Line 75:


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>PROC Reverse(CHAR ARRAY src,dst)
<syntaxhighlight lang="action!">PROC Reverse(CHAR ARRAY src,dst)
BYTE i,j,k,beg,end
BYTE i,j,k,beg,end


Line 123: Line 123:
Test("")
Test("")
Test("Frost Robert -----------------------")
Test("Frost Robert -----------------------")
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Reverse_words_in_a_string.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Reverse_words_in_a_string.png Screenshot from Atari 8-bit computer]
Line 145: Line 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]].
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]].


<lang Ada>package Simple_Parse is
<syntaxhighlight lang="ada">package Simple_Parse is
-- a very simplistic parser, useful to split a string into words
-- a very simplistic parser, useful to split a string into words
Line 155: Line 155:
-- else Next_Word sets Point to S'Last+1 and returns ""
-- else Next_Word sets Point to S'Last+1 and returns ""
end Simple_Parse;</lang>
end Simple_Parse;</syntaxhighlight>


The implementation of "Simple_Parse":
The implementation of "Simple_Parse":


<lang Ada>package body Simple_Parse is
<syntaxhighlight lang="ada">package body Simple_Parse is
function Next_Word(S: String; Point: in out Positive) return String is
function Next_Word(S: String; Point: in out Positive) return String is
Line 178: Line 178:
end Next_Word;
end Next_Word;
end Simple_Parse;</lang>
end Simple_Parse;</syntaxhighlight>


===Main Program===
===Main Program===


<lang Ada>with Ada.Text_IO, Simple_Parse;
<syntaxhighlight lang="ada">with Ada.Text_IO, Simple_Parse;


procedure Reverse_Words is
procedure Reverse_Words is
Line 202: Line 202:
Put_Line(Reverse_Words(Get_Line)); -- poem is read from standard input
Put_Line(Reverse_Words(Get_Line)); -- poem is read from standard input
end loop;
end loop;
end Reverse_Words;</lang>
end Reverse_Words;</syntaxhighlight>


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>integer j;
<syntaxhighlight lang="aime">integer j;
list l, x;
list l, x;
text s, t;
text s, t;
Line 227: Line 227:
}
}
o_newline();
o_newline();
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>------------ Fire and Ice ----------
<pre>------------ Fire and Ice ----------
Line 241: Line 241:


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
<lang algol68># returns original phrase with the order of the words reversed #
<syntaxhighlight lang="algol68"># returns original phrase with the order of the words reversed #
# a word is a sequence of non-blank characters #
# a word is a sequence of non-blank characters #
PROC reverse word order = ( STRING original phrase )STRING:
PROC reverse word order = ( STRING original phrase )STRING:
Line 284: Line 284:
print( ( reverse word order ( " " ), newline ) );
print( ( reverse word order ( " " ), newline ) );
print( ( reverse word order ( "Frost Robert -----------------------" ), newline ) )
print( ( reverse word order ( "Frost Robert -----------------------" ), newline ) )
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 301: Line 301:
=={{header|AppleScript}}==
=={{header|AppleScript}}==


<lang AppleScript>on run
<syntaxhighlight lang="applescript">on run


unlines(map(reverseWords, |lines|("---------- Ice and Fire ------------
unlines(map(reverseWords, |lines|("---------- Ice and Fire ------------
Line 392: Line 392:
end if
end if
end mReturn
end mReturn
</syntaxhighlight>
</lang>
{{out}}
{{out}}


Line 407: Line 407:


=={{header|Applesoft BASIC}}==
=={{header|Applesoft BASIC}}==
<lang ApplesoftBasic>100 DATA"---------- ICE AND FIRE ------------"
<syntaxhighlight lang="applesoftbasic">100 DATA"---------- ICE AND FIRE ------------"
110 DATA" "
110 DATA" "
120 DATA"FIRE, IN END WILL WORLD THE SAY SOME"
120 DATA"FIRE, IN END WILL WORLD THE SAY SOME"
Line 433: Line 433:
350 IF C$ <> " " THEN W$ = C$ + W$ : NEXT I
350 IF C$ <> " " THEN W$ = C$ + W$ : NEXT I
360 RETURN
360 RETURN
</syntaxhighlight>
</lang>


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>text: {
<syntaxhighlight lang="rebol">text: {
---------- Ice and Fire ------------
---------- Ice and Fire ------------
Line 451: Line 451:
[join.with:" " reverse split.words &]
[join.with:" " reverse split.words &]


print join.with:"\n" reversed</lang>
print join.with:"\n" reversed</syntaxhighlight>


{{out}}
{{out}}
Line 467: Line 467:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>Data := "
<syntaxhighlight lang="autohotkey">Data := "
(Join`r`n
(Join`r`n
---------- Ice and Fire ------------
---------- Ice and Fire ------------
Line 487: Line 487:
Output .= Line "`n", Line := ""
Output .= Line "`n", Line := ""
}
}
MsgBox, % RTrim(Output, "`n")</lang>
MsgBox, % RTrim(Output, "`n")</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f REVERSE_WORDS_IN_A_STRING.AWK
# syntax: GAWK -f REVERSE_WORDS_IN_A_STRING.AWK
BEGIN {
BEGIN {
Line 513: Line 513:
exit(0)
exit(0)
}
}
</syntaxhighlight>
</lang>
{{Output}}
{{Output}}
<pre>
<pre>
Line 529: Line 529:


=={{header|BaCon}}==
=={{header|BaCon}}==
<lang qbasic>
<syntaxhighlight lang="qbasic">
PRINT REV$("---------- Ice and Fire ------------")
PRINT REV$("---------- Ice and Fire ------------")
PRINT
PRINT
Line 540: Line 540:
PRINT
PRINT
PRINT REV$("Frost Robert -----------------------")
PRINT REV$("Frost Robert -----------------------")
</syntaxhighlight>
</lang>
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).
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}}
{{out}}
Line 557: Line 557:


=={{header|Batch File}}==
=={{header|Batch File}}==
<lang dos>@echo off
<syntaxhighlight lang="dos">@echo off


::The Main Thing...
::The Main Thing...
Line 591: Line 591:
echo.%reversed%
echo.%reversed%
goto :EOF
goto :EOF
::/The Function...</lang>
::/The Function...</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 609: Line 609:
=={{header|BASIC256}}==
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
{{trans|FreeBASIC}}
<lang BASIC256>source = freefile
<syntaxhighlight lang="basic256">source = freefile
open (source, "m:\text.txt")
open (source, "m:\text.txt")
textEnt$ = ""
textEnt$ = ""
Line 624: Line 624:
print textSal$[n];
print textSal$[n];
next n
next n
close source</lang>
close source</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> PRINT FNreverse("---------- Ice and Fire ------------")\
<syntaxhighlight lang="bbcbasic"> PRINT FNreverse("---------- Ice and Fire ------------")\
\ 'FNreverse("")\
\ 'FNreverse("")\
\ 'FNreverse("fire, in end will world the say Some")\
\ 'FNreverse("fire, in end will world the say Some")\
Line 643: Line 643:
LOCAL sp%
LOCAL sp%
sp%=INSTR(s$," ")
sp%=INSTR(s$," ")
IF sp% THEN =FNreverse(MID$(s$,sp%+1))+" "+LEFT$(s$,sp%-1) ELSE =s$</lang>
IF sp% THEN =FNreverse(MID$(s$,sp%+1))+" "+LEFT$(s$,sp%-1) ELSE =s$</syntaxhighlight>


{{out}}
{{out}}
Line 658: Line 658:


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang bracmat>("---------- Ice and Fire ------------
<syntaxhighlight lang="bracmat">("---------- Ice and Fire ------------
fire, in end will world the say Some
fire, in end will world the say Some
Line 694: Line 694:
& !output reverse$!text:?output
& !output reverse$!text:?output
& out$str$!output
& out$str$!output
);</lang>
);</syntaxhighlight>
{{out}}
{{out}}
<pre>------------ Fire and Ice ----------
<pre>------------ Fire and Ice ----------
Line 708: Line 708:


=={{header|Burlesque}}==
=={{header|Burlesque}}==
<lang blsq>
<syntaxhighlight lang="blsq">
blsq ) "It is not raining"wd<-wd
blsq ) "It is not raining"wd<-wd
"raining not is It"
"raining not is It"
blsq ) "ice. in say some"wd<-wd
blsq ) "ice. in say some"wd<-wd
"some say in ice."
"some say in ice."
</syntaxhighlight>
</lang>


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <ctype.h>
#include <ctype.h>


Line 750: Line 750:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
Output is the same as everyone else's.
Output is the same as everyone else's.


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;


public class ReverseWordsInString
public class ReverseWordsInString
Line 780: Line 780:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>
<syntaxhighlight lang="cpp">
#include <algorithm>
#include <algorithm>
#include <functional>
#include <functional>
Line 844: Line 844:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>


===Alternate version===
===Alternate version===
<lang cpp>
<syntaxhighlight lang="cpp">
#include <string>
#include <string>
#include <iostream>
#include <iostream>
Line 888: Line 888:
return system( "pause" );
return system( "pause" );
}
}
</syntaxhighlight>
</lang>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>
<syntaxhighlight lang="clojure">
(def poem
(def poem
"---------- Ice and Fire ------------
"---------- Ice and Fire ------------
Line 906: Line 906:
(dorun
(dorun
(map println (map #(apply str (interpose " " (reverse (re-seq #"[^\s]+" %)))) (clojure.string/split poem #"\n"))))
(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.
Output is the same as everyone else's.


=={{header|COBOL}}==
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
<lang COBOL>
program-id. rev-word.
program-id. rev-word.
data division.
data division.
Line 973: Line 973:
.
.
end program rev-word.
end program rev-word.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 990: Line 990:
=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
{{trans|JavaScript}}
{{trans|JavaScript}}
<lang coffeescript>strReversed = '---------- Ice and Fire ------------\n\n
<syntaxhighlight lang="coffeescript">strReversed = '---------- Ice and Fire ------------\n\n
fire, in end will world the say Some\n
fire, in end will world the say Some\n
ice. in say Some\n
ice. in say Some\n
Line 1,001: Line 1,001:
s.split('\n').map((l) -> l.split(/\s/).reverse().join ' ').join '\n'
s.split('\n').map((l) -> l.split(/\s/).reverse().join ' ').join '\n'


console.log reverseString(strReversed)</lang>
console.log reverseString(strReversed)</syntaxhighlight>
{{out}}
{{out}}
As JavaScript.
As JavaScript.


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun split-and-reverse (str)
<syntaxhighlight lang="lisp">(defun split-and-reverse (str)
(labels
(labels
((iter (s lst)
((iter (s lst)
Line 1,034: Line 1,034:
(loop for line = (read-line s NIL)
(loop for line = (read-line s NIL)
while line
while line
do (format t "~{~a~#[~:; ~]~}~%" (split-and-reverse line))))</lang>
do (format t "~{~a~#[~:; ~]~}~%" (split-and-reverse line))))</syntaxhighlight>


Output is the same as everyone else's.
Output is the same as everyone else's.


=={{header|D}}==
=={{header|D}}==
<lang d>void main() {
<syntaxhighlight lang="d">void main() {
import std.stdio, std.string, std.range, std.algorithm;
import std.stdio, std.string, std.range, std.algorithm;


Line 1,056: Line 1,056:
writefln("%(%-(%s %)\n%)",
writefln("%(%-(%s %)\n%)",
text.splitLines.map!(r => r.split.retro));
text.splitLines.map!(r => r.split.retro));
}</lang>
}</syntaxhighlight>
The output is the same as the Python entry.
The output is the same as the Python entry.
=={{header|Delphi}}==
=={{header|Delphi}}==
<lang Delphi>program RosettaCode_ReverseWordsInAString;
<syntaxhighlight lang="delphi">program RosettaCode_ReverseWordsInAString;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 1,097: Line 1,097:
end;
end;
ReadLn;
ReadLn;
end.</lang>
end.</syntaxhighlight>
The output is the same as the Pascal entry.
The output is the same as the Pascal entry.


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
Using a here-string input :
Using a here-string input :
<lang scheme>
<syntaxhighlight lang="scheme">
(define S #<<
(define S #<<
---------- Ice and Fire ------------
---------- Ice and Fire ------------
Line 1,119: Line 1,119:
(for/list ((line (string-split S "\n")))
(for/list ((line (string-split S "\n")))
(string-join (reverse (string-split line " ")) " ")))
(string-join (reverse (string-split line " ")) " ")))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,136: Line 1,136:
=={{header|Elena}}==
=={{header|Elena}}==
ELENA 5.0:
ELENA 5.0:
<lang elena>import extensions;
<syntaxhighlight lang="elena">import extensions;
import system'routines;
import system'routines;
Line 1,160: Line 1,160:
console.writeLine()
console.writeLine()
}
}
}</lang>
}</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>defmodule RC do
<syntaxhighlight lang="elixir">defmodule RC do
def reverse_words(txt) do
def reverse_words(txt) do
txt |> String.split("\n") # split lines
txt |> String.split("\n") # split lines
Line 1,172: Line 1,172:
|> Enum.join("\n") # rejoin lines
|> Enum.join("\n") # rejoin lines
end
end
end</lang>
end</syntaxhighlight>
Usage:
Usage:
<lang elixir>txt = """
<syntaxhighlight lang="elixir">txt = """
---------- Ice and Fire ------------
---------- Ice and Fire ------------
Line 1,187: Line 1,187:
"""
"""


IO.puts RC.reverse_words(txt)</lang>
IO.puts RC.reverse_words(txt)</syntaxhighlight>


=={{header|Elm}}==
=={{header|Elm}}==


<lang elm>
<syntaxhighlight lang="elm">
reversedPoem =
reversedPoem =
String.trim """
String.trim """
Line 1,214: Line 1,214:
poem =
poem =
reverseLinesWords reversedPoem
reverseLinesWords reversedPoem
</syntaxhighlight>
</lang>


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==


<lang Lisp>(defun reverse-words (line)
<syntaxhighlight lang="lisp">(defun reverse-words (line)
(insert
(insert
(format "%s\n"
(format "%s\n"
Line 1,236: Line 1,236:
"... elided paragraph last ..."
"... elided paragraph last ..."
""
""
"Frost Robert ----------------------- "))</lang>
"Frost Robert ----------------------- "))</syntaxhighlight>


{{out}}
{{out}}
Line 1,254: Line 1,254:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>
<syntaxhighlight lang="fsharp">
//Reverse words in a string. Nigel Galloway: July 14th., 2021
//Reverse words in a string. Nigel Galloway: July 14th., 2021
[" ---------- Ice and Fire ------------ ";
[" ---------- Ice and Fire ------------ ";
Line 1,266: Line 1,266:
" ";
" ";
" Frost Robert ----------------------- "]|>List.map(fun n->n.Split " "|>Array.filter((<>)"")|>Array.rev|>String.concat " ")|>List.iter(printfn "%s")
" Frost Robert ----------------------- "]|>List.map(fun n->n.Split " "|>Array.filter((<>)"")|>Array.rev|>String.concat " ")|>List.iter(printfn "%s")
</lang>
</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,281: Line 1,281:
</pre>
</pre>
=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: io sequences splitting ;
<syntaxhighlight lang="factor">USING: io sequences splitting ;
IN: rosetta-code.reverse-words
IN: rosetta-code.reverse-words


Line 1,295: Line 1,295:
Frost Robert -----------------------"
Frost Robert -----------------------"


"\n" split [ " " split reverse " " join ] map [ print ] each</lang>
"\n" split [ " " split reverse " " join ] map [ print ] each</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,312: Line 1,312:
=={{header|Forth}}==
=={{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.
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.
<lang>: not-empty? dup 0 > ;
<syntaxhighlight lang="text">: not-empty? dup 0 > ;
: (reverse) parse-name not-empty? IF recurse THEN type space ;
: (reverse) parse-name not-empty? IF recurse THEN type space ;
: reverse (reverse) cr ;
: reverse (reverse) cr ;
Line 1,325: Line 1,325:
reverse ... elided paragraph last ...
reverse ... elided paragraph last ...
reverse
reverse
reverse Frost Robert -----------------------</lang>
reverse Frost Robert -----------------------</syntaxhighlight>


'''Output'''
'''Output'''
Line 1,346: Line 1,346:
Fortran syntax is mostly Fortran 77.
Fortran syntax is mostly Fortran 77.


<lang fortran>
<syntaxhighlight lang="fortran">
character*40 words
character*40 words
character*40 reversed
character*40 reversed
Line 1,375: Line 1,375:
end
end


</syntaxhighlight>
</lang>


Output from comand: <b>cat frostPoem.txt | reverse</b><p>
Output from comand: <b>cat frostPoem.txt | reverse</b><p>
Line 1,396: Line 1,396:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Sub split (s As String, sepList As String, result() As String, removeEmpty As Boolean = False)
Sub split (s As String, sepList As String, result() As String, removeEmpty As Boolean = False)
Line 1,447: Line 1,447:
Print
Print
Print "Press any key to quit"
Print "Press any key to quit"
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 1,456: Line 1,456:


=={{header|Frink}}==
=={{header|Frink}}==
<lang frink>
<syntaxhighlight lang="frink">
lines=split["\n",
lines=split["\n",
"""---------- Ice and Fire ------------
"""---------- Ice and Fire ------------
Line 1,471: Line 1,471:
for line = lines
for line = lines
println[join[" ", reverse[split[%r/\s+/, line]]]]
println[join[" ", reverse[split[%r/\s+/, line]]]]
</syntaxhighlight>
</lang>


=={{header|FutureBasic}}==
=={{header|FutureBasic}}==
<lang futurebasic>
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
include "NSLog.incl"


Line 1,507: Line 1,507:


HandleEvents
HandleEvents
</syntaxhighlight>
</lang>


Output:
Output:
Line 1,525: Line 1,525:
=={{header|Gambas}}==
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=c81c1bbf94e856035fd382015d208272 Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=c81c1bbf94e856035fd382015d208272 Click this link to run this code]'''
<lang gambas>Public Sub Main()
<syntaxhighlight lang="gambas">Public Sub Main()
Dim sString As New String[10] 'Array for the input text
Dim sString As New String[10] 'Array for the input text
Dim sLine As New String[] 'Array of each word in a line
Dim sLine As New String[] 'Array of each word in a line
Line 1,560: Line 1,560:
Print sOutput 'Print the output
Print sOutput 'Print the output


End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,576: Line 1,576:


=={{header|Gema}}==
=={{header|Gema}}==
<lang gema>\L<G> <U>=@{$2} $1</lang>
<syntaxhighlight lang="gema">\L<G> <U>=@{$2} $1</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,614: Line 1,614:
fmt.Println(t)
fmt.Println(t)
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,630: Line 1,630:


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang groovy>def text = new StringBuilder()
<syntaxhighlight lang="groovy">def text = new StringBuilder()
.append('---------- Ice and Fire ------------\n')
.append('---------- Ice and Fire ------------\n')
.append(' \n')
.append(' \n')
Line 1,644: Line 1,644:
text.eachLine { line ->
text.eachLine { line ->
println "$line --> ${line.split(' ').reverse().join(' ')}"
println "$line --> ${line.split(' ').reverse().join(' ')}"
}</lang>
}</syntaxhighlight>
{{output}}
{{output}}
<pre>---------- Ice and Fire ------------ --> ------------ Fire and Ice ----------
<pre>---------- Ice and Fire ------------ --> ------------ Fire and Ice ----------
Line 1,658: Line 1,658:


=={{header|Haskell}}==
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">
<lang Haskell>
revstr :: String -> String
revstr :: String -> String
revstr = unwords . reverse . words -- point-free style
revstr = unwords . reverse . words -- point-free style
Line 1,677: Line 1,677:
\\n\
\\n\
\Frost Robert -----------------------\n" --multiline string notation requires \ at end and start of lines, and \n to be manually input
\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.
unwords, reverse, words, unlines, map and lines are built-in functions, all available at GHC's Prelude.
For better visualization, use "putStr test"
For better visualization, use "putStr test"
Line 1,684: Line 1,684:


Works in both languages:
Works in both languages:
<lang unicon>procedure main()
<syntaxhighlight lang="unicon">procedure main()
every write(rWords(&input))
every write(rWords(&input))
end
end
Line 1,697: Line 1,697:
procedure genWords()
procedure genWords()
while w := 1(tab(upto(" \t")),tab(many(" \t"))) || " " do suspend w
while w := 1(tab(upto(" \t")),tab(many(" \t"))) || " " do suspend w
end</lang>
end</syntaxhighlight>


{{out}} for test file:
{{out}} for test file:
Line 1,719: Line 1,719:
Treated interactively:
Treated interactively:


<lang J> ([:;@|.[:<;.1 ' ',]);._2]0 :0
<syntaxhighlight lang="j"> ([:;@|.[:<;.1 ' ',]);._2]0 :0
---------- Ice and Fire ------------
---------- Ice and Fire ------------


Line 1,741: Line 1,741:
----------------------- Robert Frost
----------------------- 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.
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.
Line 1,747: Line 1,747:
Another approach:
Another approach:


<lang J>echo ;:inv@|.@cut;._2 {{)n
<syntaxhighlight lang="j">echo ;:inv@|.@cut;._2 {{)n
---------- Ice and Fire ------------
---------- Ice and Fire ------------
Line 1,758: Line 1,758:
Frost Robert -----------------------
Frost Robert -----------------------
}}</lang>
}}</syntaxhighlight>


produces:
produces:
Line 1,776: Line 1,776:


=={{header|Java}}==
=={{header|Java}}==
<lang java>public class ReverseWords {
<syntaxhighlight lang="java">public class ReverseWords {


static final String[] lines = {
static final String[] lines = {
Line 1,797: Line 1,797:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{works with|Java|8+}}
{{works with|Java|8+}}
<lang java>package string;
<syntaxhighlight lang="java">package string;


import static java.util.Arrays.stream;
import static java.util.Arrays.stream;
Line 1,837: Line 1,837:
;
;
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,853: Line 1,853:


=={{header|JavaScript}}==
=={{header|JavaScript}}==
<lang javascript>var strReversed =
<syntaxhighlight lang="javascript">var strReversed =
"---------- Ice and Fire ------------\n\
"---------- Ice and Fire ------------\n\
\n\
\n\
Line 1,875: Line 1,875:
console.log(
console.log(
reverseString(strReversed)
reverseString(strReversed)
);</lang>
);</syntaxhighlight>


Output:
Output:
Line 1,890: Line 1,890:


=={{header|jq}}==
=={{header|jq}}==
<lang jq>split("[ \t\n\r]+") | reverse | join(" ")</lang>
<syntaxhighlight lang="jq">split("[ \t\n\r]+") | reverse | join(" ")</syntaxhighlight>
This solution requires a version of jq with regex support for split.
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.<lang sh>$ jq -R -r -M -f reverse_words.jq IceAndFire.txt
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.<syntaxhighlight lang="sh">$ jq -R -r -M -f reverse_words.jq IceAndFire.txt
------------ Fire and Ice ----------
------------ Fire and Ice ----------


Line 1,903: Line 1,903:
... last paragraph elided ...
... last paragraph elided ...


----------------------- Robert Frost</lang>
----------------------- Robert Frost</syntaxhighlight>


=={{header|Jsish}}==
=={{header|Jsish}}==
From Javascript entry.
From Javascript entry.
<lang javascript>var strReversed =
<syntaxhighlight lang="javascript">var strReversed =
"---------- Ice and Fire ------------\n
"---------- Ice and Fire ------------\n
fire, in end will world the say Some
fire, in end will world the say Some
Line 1,952: Line 1,952:
----------------------- Robert Frost
----------------------- Robert Frost
=!EXPECTEND!=
=!EXPECTEND!=
*/</lang>
*/</syntaxhighlight>


{{out}}
{{out}}
Line 1,960: Line 1,960:


=={{header|Julia}}==
=={{header|Julia}}==
<lang Julia>revstring (str) = join(reverse(split(str, " ")), " ")</lang>{{Out}}
<syntaxhighlight lang="julia">revstring (str) = join(reverse(split(str, " ")), " ")</syntaxhighlight>{{Out}}
<pre>julia> revstring("Hey you, Bub!")
<pre>julia> revstring("Hey you, Bub!")
"Bub! you, Hey"
"Bub! you, Hey"
Line 1,991: Line 1,991:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang kotlin>fun reversedWords(s: String) = s.split(" ").filter { it.isNotEmpty() }.reversed().joinToString(" ")
<syntaxhighlight lang="kotlin">fun reversedWords(s: String) = s.split(" ").filter { it.isNotEmpty() }.reversed().joinToString(" ")


fun main() {
fun main() {
Line 2,010: Line 2,010:
)
)
sl.forEach { println(reversedWords(it)) }
sl.forEach { println(reversedWords(it)) }
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,029: Line 2,029:


=={{header|Ksh}}==
=={{header|Ksh}}==
<lang ksh>
<syntaxhighlight lang="ksh">
#!/bin/ksh
#!/bin/ksh


Line 2,059: Line 2,059:
... elided paragraph last ...
... elided paragraph last ...
Frost Robert -----------------------
Frost Robert -----------------------
EOF</lang>
EOF</syntaxhighlight>
{{out}}<pre>
{{out}}<pre>
------------ Fire and Ice ----------
------------ Fire and Ice ----------
Line 2,073: Line 2,073:
=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
This answer illustrates how a missing primitive (line_split) can be added directly in the wiki page.
This answer illustrates how a missing primitive (line_split) can be added directly in the wiki page.
<lang scheme>
<syntaxhighlight lang="scheme">
1) We write a function
1) We write a function


Line 2,142: Line 2,142:
----------------------- Robert Frost
----------------------- Robert Frost
</syntaxhighlight>
</lang>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
for i = 1 to 10
for i = 1 to 10
read string$
read string$
Line 2,172: Line 2,172:
data ""
data ""
data "Frost Robert -----------------------"
data "Frost Robert -----------------------"
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>------------ Fire and Ice ----------
<pre>------------ Fire and Ice ----------
Line 2,187: Line 2,187:
=={{header|LiveCode}}==
=={{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
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
<lang LiveCode>repeat for each line txtln in fld "Fieldtxt"
<syntaxhighlight lang="livecode">repeat for each line txtln in fld "Fieldtxt"
repeat with i = the number of words of txtln down to 1
repeat with i = the number of words of txtln down to 1
put word i of txtln & space after txtrev
put word i of txtln & space after txtrev
Line 2,193: Line 2,193:
put cr after txtrev -- preserve line
put cr after txtrev -- preserve line
end repeat
end repeat
put txtrev</lang>
put txtrev</syntaxhighlight>


=={{header|LiveScript}}==
=={{header|LiveScript}}==
<lang livescript>
<syntaxhighlight lang="livescript">
poem =
poem =
"""
"""
Line 2,214: Line 2,214:
reverse-string = (.split '\n') >> (.map reverse-words) >> (.join '\n')
reverse-string = (.split '\n') >> (.map reverse-words) >> (.join '\n')
reverse-string poem
reverse-string poem
</syntaxhighlight>
</lang>


=={{header|Logo}}==
=={{header|Logo}}==
This version just reads the words from standard input.
This version just reads the words from standard input.


<lang logo>do.until [
<syntaxhighlight lang="logo">do.until [
make "line readlist
make "line readlist
print reverse :line
print reverse :line
] [word? :line]
] [word? :line]
bye</lang>
bye</syntaxhighlight>


{{Out}}
{{Out}}
Line 2,252: Line 2,252:
See below for original entry and the input string under variable 's'. Here is a significantly shorter program.
See below for original entry and the input string under variable 's'. Here is a significantly shorter program.


<lang lua>
<syntaxhighlight lang="lua">
local lines = {}
local lines = {}
for line in (s .. "\n"):gmatch("(.-)\n") do
for line in (s .. "\n"):gmatch("(.-)\n") do
Line 2,262: Line 2,262:
end
end
print(table.concat(lines, "\n"))
print(table.concat(lines, "\n"))
</syntaxhighlight>
</lang>




Line 2,282: Line 2,282:
]]
]]


<lang lua>function table.reverse(a)
<syntaxhighlight lang="lua">function table.reverse(a)
local res = {}
local res = {}
for i = #a, 1, -1 do
for i = #a, 1, -1 do
Line 2,300: Line 2,300:
for line, nl in s:gmatch("([^\n]-)(\n)") do
for line, nl in s:gmatch("([^\n]-)(\n)") do
print(table.concat(table.reverse(splittokens(line)), ' '))
print(table.concat(table.reverse(splittokens(line)), ' '))
end</lang>
end</syntaxhighlight>


''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.
''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|Maple}}==
=={{header|Maple}}==
<lang Maple>while (true) do
<syntaxhighlight lang="maple">while (true) do
input := readline("input.txt"):
input := readline("input.txt"):
if input = 0 then break: fi:
if input = 0 then break: fi:
Line 2,311: Line 2,311:
input := StringTools:-Join(ListTools:-Reverse(StringTools:-Split(input, " "))," "):
input := StringTools:-Join(ListTools:-Reverse(StringTools:-Split(input, " "))," "):
printf("%s\n", input):
printf("%s\n", input):
od:</lang>
od:</syntaxhighlight>
{{Out|Output}}
{{Out|Output}}
<pre>------------ Fire and Ice ----------
<pre>------------ Fire and Ice ----------
Line 2,325: Line 2,325:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>poem = "---------- Ice and Fire ------------
<syntaxhighlight lang="mathematica">poem = "---------- Ice and Fire ------------
fire, in end will world the say Some
fire, in end will world the say Some
Line 2,340: Line 2,340:
linesWithReversedWords =
linesWithReversedWords =
StringJoin[Riffle[#, " "]] & /@ reversedWordArray;
StringJoin[Riffle[#, " "]] & /@ reversedWordArray;
finaloutput = StringJoin[Riffle[#, "\n"]] & @ linesWithReversedWords</lang>
finaloutput = StringJoin[Riffle[#, "\n"]] & @ linesWithReversedWords</syntaxhighlight>
{{out}}
{{out}}
<pre>------------ Fire and Ice ----------
<pre>------------ Fire and Ice ----------
Line 2,354: Line 2,354:


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
<lang MATLAB>function testReverseWords
<syntaxhighlight lang="matlab">function testReverseWords
testStr = {'---------- Ice and Fire ------------' ; ...
testStr = {'---------- Ice and Fire ------------' ; ...
'' ; ...
'' ; ...
Line 2,378: Line 2,378:
strOut = strtrim(sprintf('%s ', words{end:-1:1}));
strOut = strtrim(sprintf('%s ', words{end:-1:1}));
end
end
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>------------ Fire and Ice ----------
<pre>------------ Fire and Ice ----------
Line 2,392: Line 2,392:


=={{header|MAXScript}}==
=={{header|MAXScript}}==
<lang maxscript>
<syntaxhighlight lang="maxscript">
-- MAXScript : Reverse words in a string : N.H. 2019
-- MAXScript : Reverse words in a string : N.H. 2019
--
--
Line 2,418: Line 2,418:
) -- end of while eof
) -- end of while eof
)
)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
Output to MAXScript Listener:
Output to MAXScript Listener:
Line 2,433: Line 2,433:


=={{header|MiniScript}}==
=={{header|MiniScript}}==
<lang MiniScript>lines = ["==========================================",
<syntaxhighlight lang="miniscript">lines = ["==========================================",
"| ---------- Ice and Fire ------------ |",
"| ---------- Ice and Fire ------------ |",
"| |",
"| |",
Line 2,457: Line 2,457:
end while
end while
print newLine.join
print newLine.join
end for</lang>
end for</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,477: Line 2,477:
{{trans|Pascal}}
{{trans|Pascal}}
{{works with|ADW Modula-2|any (Compile with the linker option ''Console Application'').}}
{{works with|ADW Modula-2|any (Compile with the linker option ''Console Application'').}}
<lang modula2>
<syntaxhighlight lang="modula2">
MODULE ReverseWords;
MODULE ReverseWords;


Line 2,536: Line 2,536:
END;
END;
END ReverseWords.
END ReverseWords.
</syntaxhighlight>
</lang>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<lang nanoquery>def reverse_words(string)
<syntaxhighlight lang="nanoquery">def reverse_words(string)
tokens = split(string, " ")
tokens = split(string, " ")
if len(tokens) = 0
if len(tokens) = 0
Line 2,564: Line 2,564:
for line in split(data, "\n")
for line in split(data, "\n")
println reverse_words(line)
println reverse_words(line)
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>------------ Fire and Ice ----------
<pre>------------ Fire and Ice ----------
Line 2,580: Line 2,580:
{{works with|Q'Nial Version 6.3}}
{{works with|Q'Nial Version 6.3}}


<syntaxhighlight lang="nial">
<lang Nial>
# Define a function to convert a list of strings to a single string.
# Define a function to convert a list of strings to a single string.
join is rest link (' ' eachboth link)
join is rest link (' ' eachboth link)
Line 2,599: Line 2,599:
'' \
'' \
'Poe Edgar -----------------------'
'Poe Edgar -----------------------'
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,618: Line 2,618:


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import strutils
<syntaxhighlight lang="nim">import strutils


let text = """---------- Ice and Fire ------------
let text = """---------- Ice and Fire ------------
Line 2,644: Line 2,644:


for line in text.splitLines():
for line in text.splitLines():
echo line.split(' ').reversed().join(" ")</lang>
echo line.split(' ').reversed().join(" ")</syntaxhighlight>
{{out}}
{{out}}
<pre>------------ Fire and Ice ----------
<pre>------------ Fire and Ice ----------
Line 2,658: Line 2,658:


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>use Collection;
<syntaxhighlight lang="objeck">use Collection;


class Reverselines {
class Reverselines {
Line 2,686: Line 2,686:
};
};
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,701: Line 2,701:


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>#load "str.cma"
<syntaxhighlight lang="ocaml">#load "str.cma"
let input = ["---------- Ice and Fire ------------";
let input = ["---------- Ice and Fire ------------";
"";
"";
Line 2,716: Line 2,716:
let reversed = List.map List.rev splitted in
let reversed = List.map List.rev splitted in
let final = List.map (String.concat " ") reversed in
let final = List.map (String.concat " ") reversed in
List.iter print_endline final;;</lang>
List.iter print_endline final;;</syntaxhighlight>
Sample usage
Sample usage
<pre>$ ocaml reverse.ml
<pre>$ ocaml reverse.ml
Line 2,733: Line 2,733:
=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>: revWords(s)
<syntaxhighlight lang="oforth">: revWords(s)
s words reverse unwords ;
s words reverse unwords ;


Line 2,746: Line 2,746:
"... elided paragraph last ... " revWords println
"... elided paragraph last ... " revWords println
" " revWords println
" " revWords println
"Frost Robert -----------------------" revWords println ;</lang>
"Frost Robert -----------------------" revWords println ;</syntaxhighlight>


{{out}}
{{out}}
Line 2,766: Line 2,766:
=={{header|Pascal}}==
=={{header|Pascal}}==
Free Pascal 3.0.0
Free Pascal 3.0.0
<lang pascal>program Reverse_words(Output);
<syntaxhighlight lang="pascal">program Reverse_words(Output);
{$H+}
{$H+}


Line 2,811: Line 2,811:
end;
end;
readln;
readln;
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>----------- Fire and Ice ----------
<pre>----------- Fire and Ice ----------
Line 2,825: Line 2,825:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>print join(" ", reverse split), "\n" for <DATA>;
<syntaxhighlight lang="perl">print join(" ", reverse split), "\n" for <DATA>;
__DATA__
__DATA__
---------- Ice and Fire ------------
---------- Ice and Fire ------------
Line 2,837: Line 2,837:
Frost Robert -----------------------
Frost Robert -----------------------
</syntaxhighlight>
</lang>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">test</span><span style="color: #0000FF;">=</span><span style="color: #008000;">"""
<span style="color: #008080;">constant</span> <span style="color: #000000;">test</span><span style="color: #0000FF;">=</span><span style="color: #008000;">"""
Line 2,859: Line 2,859:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,875: Line 2,875:


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<lang Phixmonti>include ..\Utilitys.pmt
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt


"---------- Ice and Fire ------------"
"---------- Ice and Fire ------------"
Line 2,897: Line 2,897:
else drop endif
else drop endif
drop nl
drop nl
endfor</lang>
endfor</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,913: Line 2,913:


=={{header|PHP}}==
=={{header|PHP}}==
<lang php>
<syntaxhighlight lang="php">
<?php
<?php
Line 2,941: Line 2,941:




echo strInv($string);</lang>
echo strInv($string);</syntaxhighlight>
'''Output''':
'''Output''':


<lang Shell>------------ Fire and Ice ----------
<syntaxhighlight lang="shell">------------ Fire and Ice ----------


Some say the world will end in fire,
Some say the world will end in fire,
Line 2,953: Line 2,953:
... last paragraph elided ...
... last paragraph elided ...


----------------------- Robert Frost</lang>
----------------------- Robert Frost</syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<syntaxhighlight lang="picolisp">
<lang PicoLisp>
(in "FireIce.txt"
(in "FireIce.txt"
(until (eof)
(until (eof)
(prinl (glue " " (flip (split (line) " "))))))
(prinl (glue " " (flip (split (line) " "))))))
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
Same as anybody else.
Same as anybody else.


=={{header|Pike}}==
=={{header|Pike}}==
<lang Pike>string story = #"---------- Ice and Fire ------------
<syntaxhighlight lang="pike">string story = #"---------- Ice and Fire ------------
fire, in end will world the say Some
fire, in end will world the say Some
Line 2,978: Line 2,978:
foreach(story/"\n", string line)
foreach(story/"\n", string line)
write("%s\n", reverse(line/" ")*" ");
write("%s\n", reverse(line/" ")*" ");
</syntaxhighlight>
</lang>


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang PL/I>rev: procedure options (main); /* 5 May 2014 */
<syntaxhighlight lang="pl/i">rev: procedure options (main); /* 5 May 2014 */
declare (s, reverse) character (50) varying;
declare (s, reverse) character (50) varying;
declare (i, j) fixed binary;
declare (i, j) fixed binary;
Line 3,013: Line 3,013:
put edit ('---> ', reverse) (col(40), 2 A);
put edit ('---> ', reverse) (col(40), 2 A);
end;
end;
end rev;</lang>
end rev;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,030: Line 3,030:
=={{header|PowerShell}}==
=={{header|PowerShell}}==
{{works with|PowerShell|4.0}}
{{works with|PowerShell|4.0}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
Function Reverse-Words($lines) {
Function Reverse-Words($lines) {
$lines | foreach {
$lines | foreach {
Line 3,051: Line 3,051:


Reverse-Words($lines)
Reverse-Words($lines)
</syntaxhighlight>
</lang>


'''output''' :
'''output''' :
Line 3,068: Line 3,068:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang purebasic>a$ = "---------- Ice and Fire ------------" +#CRLF$+
<syntaxhighlight lang="purebasic">a$ = "---------- Ice and Fire ------------" +#CRLF$+
" " +#CRLF$+
" " +#CRLF$+
"fire, in end will world the say Some" +#CRLF$+
"fire, in end will world the say Some" +#CRLF$+
Line 3,089: Line 3,089:
Next
Next
Input()
Input()
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,107: Line 3,107:


=={{header|Python}}==
=={{header|Python}}==
<lang python> text = '''\
<syntaxhighlight lang="python"> text = '''\
---------- Ice and Fire ------------
---------- Ice and Fire ------------


Line 3,119: Line 3,119:
Frost Robert -----------------------'''
Frost Robert -----------------------'''


for line in text.split('\n'): print(' '.join(line.split()[::-1]))</lang>
for line in text.split('\n'): print(' '.join(line.split()[::-1]))</syntaxhighlight>


'''Output''':
'''Output''':


<lang Shell>------------ Fire and Ice ----------
<syntaxhighlight lang="shell">------------ Fire and Ice ----------


Some say the world will end in fire,
Some say the world will end in fire,
Line 3,132: Line 3,132:
... last paragraph elided ...
... last paragraph elided ...


----------------------- Robert Frost</lang>
----------------------- Robert Frost</syntaxhighlight>


=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery> ' [ $ " ---------- Ice and Fire ------------ "
<syntaxhighlight lang="quackery"> ' [ $ " ---------- Ice and Fire ------------ "
$ ""
$ ""
$ " fire, in end will world the say Some "
$ " fire, in end will world the say Some "
Line 3,151: Line 3,151:
witheach
witheach
[ echo$ sp ]
[ echo$ sp ]
cr ]</lang>
cr ]</syntaxhighlight>


{{out}}
{{out}}
Line 3,168: Line 3,168:
=={{header|R}}==
=={{header|R}}==


<syntaxhighlight lang="r">
<lang R>
whack <- function(s) {
whack <- function(s) {
paste( rev( unlist(strsplit(s, " "))), collapse=' ' ) }
paste( rev( unlist(strsplit(s, " "))), collapse=' ' ) }
Line 3,187: Line 3,187:


for (line in poem) cat( whack(line), "\n" )
for (line in poem) cat( whack(line), "\n" )
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,208: Line 3,208:
(Everything that happens in R is a function-call.)
(Everything that happens in R is a function-call.)


<syntaxhighlight lang="r">
<lang R>
> `{` <- function(s) rev(unlist(strsplit(s, " ")))
> `{` <- function(s) rev(unlist(strsplit(s, " ")))
> {"one two three four five"}
> {"one two three four five"}
[1] "five" "four" "three" "two" "one"
[1] "five" "four" "three" "two" "one"
</syntaxhighlight>
</lang>


You had better restart your REPL after trying this.
You had better restart your REPL after trying this.


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>#lang racket/base
<syntaxhighlight lang="racket">#lang racket/base


(require racket/string)
(require racket/string)
Line 3,244: Line 3,244:
(begin (displayln (split-reverse l))
(begin (displayln (split-reverse l))
(loop (read-line poem-port))))))
(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):
In Wheeler-readable/sweet notation (https://readable.sourceforge.io/) as implemented by Asumu Takikawa (https://github.com/takikawa/sweet-racket):
<lang racket>
<syntaxhighlight lang="racket">
#lang sweet-exp racket/base
#lang sweet-exp racket/base
require racket/string
require racket/string
Line 3,276: Line 3,276:
displayln split-reverse(l)
displayln split-reverse(l)
loop read-line(poem-port)
loop read-line(poem-port)
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
We'll read input from stdin
We'll read input from stdin
<lang perl6>say ~.words.reverse for lines</lang>
<syntaxhighlight lang="raku" line>say ~.words.reverse for lines</syntaxhighlight>
{{out}}
{{out}}
<pre>------------ Fire and Ice ----------
<pre>------------ Fire and Ice ----------
Line 3,295: Line 3,295:


=={{header|Red}}==
=={{header|Red}}==
<lang Red>Red []
<syntaxhighlight lang="red">Red []
foreach line
foreach line
split
split
Line 3,310: Line 3,310:
print reverse split line " "
print reverse split line " "
]
]
</syntaxhighlight>
</lang>


=={{header|REXX}}==
=={{header|REXX}}==
===natural order===
===natural order===
This REXX version process the words in a natural order (first to last).
This REXX version process the words in a natural order (first to last).
<lang rexx>/*REXX program reverses the order of tokens in a string (but not the letters).*/
<syntaxhighlight lang="rexx">/*REXX program reverses the order of tokens in a string (but not the letters).*/
@.=; @.1 = "---------- Ice and Fire ------------"
@.=; @.1 = "---------- Ice and Fire ------------"
@.2 = ' '
@.2 = ' '
Line 3,334: Line 3,334:


say $ /*display the newly constructed line. */
say $ /*display the newly constructed line. */
end /*j*/ /*stick a fork in it, we're all done. */</lang>
end /*j*/ /*stick a fork in it, we're all done. */</syntaxhighlight>
'''output''' &nbsp; when using the (internal text) ten lines of input:
'''output''' &nbsp; when using the (internal text) ten lines of input:
<pre>
<pre>
Line 3,351: Line 3,351:
===reverse order===
===reverse order===
This REXX version process the words in reverse order (last to first).
This REXX version process the words in reverse order (last to first).
<lang rexx>/*REXX program reverses the order of tokens in a string (but not the letters).*/
<syntaxhighlight lang="rexx">/*REXX program reverses the order of tokens in a string (but not the letters).*/
@.=; @.1 = "---------- Ice and Fire ------------"
@.=; @.1 = "---------- Ice and Fire ------------"
@.2 = ' '
@.2 = ' '
Line 3,370: Line 3,370:


say $ /*display the newly constructed line. */
say $ /*display the newly constructed line. */
end /*j*/ /*stick a fork in it, we're all done. */</lang>
end /*j*/ /*stick a fork in it, we're all done. */</syntaxhighlight>
'''output''' &nbsp; is the same as the 1<sup>st</sup> REXX version. <br><br>
'''output''' &nbsp; is the same as the 1<sup>st</sup> REXX version. <br><br>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
aList = str2list("
aList = str2list("
---------- Ice and Fire ------------
---------- Ice and Fire ------------
Line 3,392: Line 3,392:
for y in aList2 see y + " " next see nl
for y in aList2 see y + " " next see nl
next
next
</syntaxhighlight>
</lang>


Output
Output
<lang ring>
<syntaxhighlight lang="ring">
------------ Fire and Ice ----------
------------ Fire and Ice ----------


Line 3,405: Line 3,405:
... last paragraph elided ...
... last paragraph elided ...
----------------------- Robert Frost
----------------------- Robert Frost
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>puts <<EOS
<syntaxhighlight lang="ruby">puts <<EOS
---------- Ice and Fire ------------
---------- Ice and Fire ------------


Line 3,420: Line 3,420:
Frost Robert -----------------------
Frost Robert -----------------------
EOS
EOS
.each_line.map {|line| line.split.reverse.join(' ')}</lang>
.each_line.map {|line| line.split.reverse.join(' ')}</syntaxhighlight>


Output the same as everyone else's.
Output the same as everyone else's.


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>for i = 1 to 10
<syntaxhighlight lang="runbasic">for i = 1 to 10
read string$
read string$
j = 1
j = 1
Line 3,446: Line 3,446:
data "... elided paragraph last ..."
data "... elided paragraph last ..."
data ""
data ""
data "Frost Robert -----------------------"</lang>
data "Frost Robert -----------------------"</syntaxhighlight>
Output:
Output:
<pre>------------ Fire and Ice ----------
<pre>------------ Fire and Ice ----------
Line 3,460: Line 3,460:


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>const TEXT: &'static str =
<syntaxhighlight lang="rust">const TEXT: &'static str =
"---------- Ice and Fire ------------
"---------- Ice and Fire ------------
Line 3,482: Line 3,482:
.collect::<Vec<_>>() // Collect lines into Vec<String>
.collect::<Vec<_>>() // Collect lines into Vec<String>
.join("\n")); // Concatenate lines into String
.join("\n")); // Concatenate lines into String
}</lang>
}</syntaxhighlight>


=={{header|S-lang}}==
=={{header|S-lang}}==
<lang S-lang>variable ln, in =
<syntaxhighlight lang="s-lang">variable ln, in =
["---------- Ice and Fire ------------",
["---------- Ice and Fire ------------",
"fire, in end will world the say Some",
"fire, in end will world the say Some",
Line 3,500: Line 3,500:
array_reverse(ln);
array_reverse(ln);
() = printf("%s\n", strjoin(ln, " "));
() = printf("%s\n", strjoin(ln, " "));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>------------ Fire and Ice ----------
<pre>------------ Fire and Ice ----------
Line 3,515: Line 3,515:
{{works with|Scala|2.9.x}}
{{works with|Scala|2.9.x}}


<lang Scala>object ReverseWords extends App {
<syntaxhighlight lang="scala">object ReverseWords extends App {


"""| ---------- Ice and Fire ------------
"""| ---------- Ice and Fire ------------
Line 3,531: Line 3,531:
.foreach{println}
.foreach{println}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,550: Line 3,550:
{{works with|Gauche Scheme}}
{{works with|Gauche Scheme}}


<syntaxhighlight lang="scheme">
<lang Scheme>
(for-each
(for-each
(lambda (s) (print (string-join (reverse (string-split s #/ +/)))))
(lambda (s) (print (string-join (reverse (string-split s #/ +/)))))
Line 3,565: Line 3,565:
Frost Robert -----------------------"
Frost Robert -----------------------"
#/[ \r]*\n[ \r]*/))
#/[ \r]*\n[ \r]*/))
</syntaxhighlight>
</lang>
<b>Output:</b>
<b>Output:</b>
<pre>
<pre>
Line 3,581: Line 3,581:


=={{header|sed}}==
=={{header|sed}}==
<lang sed>#!/usr/bin/sed -f
<syntaxhighlight lang="sed">#!/usr/bin/sed -f


G
G
Line 3,587: Line 3,587:
s/^[[:space:]]*\([^[:space:]][^[:space:]]*\)\(.*\n\)/\2 \1/
s/^[[:space:]]*\([^[:space:]][^[:space:]]*\)\(.*\n\)/\2 \1/
t loop
t loop
s/^[[:space:]]*//</lang>
s/^[[:space:]]*//</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


const array string: lines is [] (
const array string: lines is [] (
Line 3,617: Line 3,617:
writeln;
writeln;
end for;
end for;
end func;</lang>
end func;</syntaxhighlight>


{{out}}
{{out}}
Line 3,634: Line 3,634:


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
<lang sensetalk>set poem to {{
<syntaxhighlight lang="sensetalk">set poem to {{
---------- Ice and Fire ------------
---------- Ice and Fire ------------


Line 3,650: Line 3,650:
put (each word of it) reversed joined by space
put (each word of it) reversed joined by space
end repeat
end repeat
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,666: Line 3,666:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>DATA.each{|line| line.words.reverse.join(" ").say};
<syntaxhighlight lang="ruby">DATA.each{|line| line.words.reverse.join(" ").say};


__DATA__
__DATA__
Line 3,678: Line 3,678:
... elided paragraph last ...
... elided paragraph last ...


Frost Robert -----------------------</lang>
Frost Robert -----------------------</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
<lang smalltalk>
<syntaxhighlight lang="smalltalk">
poem := '---------- Ice and Fire ------------
poem := '---------- Ice and Fire ------------
Line 3,694: Line 3,694:


(poem lines collect: [ :line | ((line splitOn: ' ') reverse) joinUsing: ' ' ]) joinUsing: (String cr).
(poem lines collect: [ :line | ((line splitOn: ' ') reverse) joinUsing: ' ' ]) joinUsing: (String cr).
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,714: Line 3,714:
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.)
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.)


<lang sparkling>let lines = split("---------- Ice and Fire ------------
<syntaxhighlight lang="sparkling">let lines = split("---------- Ice and Fire ------------


fire, in end will world the say Some
fire, in end will world the say Some
Line 3,733: Line 3,733:


print();
print();
});</lang>
});</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>val lines = [
<syntaxhighlight lang="sml">val lines = [
" ---------- Ice and Fire ------------ ",
" ---------- Ice and Fire ------------ ",
" ",
" ",
Line 3,751: Line 3,751:
val revWords = String.concatWith " " o rev o String.tokens Char.isSpace
val revWords = String.concatWith " " o rev o String.tokens Char.isSpace


val () = app (fn line => print (revWords line ^ "\n")) lines</lang>
val () = app (fn line => print (revWords line ^ "\n")) lines</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
<lang swift>import Foundation
<syntaxhighlight lang="swift">import Foundation


// convenience extension for better clarity
// convenience extension for better clarity
Line 3,774: Line 3,774:
let output = input.lines.map { $0.words.reverse().joinWithSeparator(" ") }.joinWithSeparator("\n")
let output = input.lines.map { $0.words.reverse().joinWithSeparator(" ") }.joinWithSeparator("\n")


print(output)</lang>
print(output)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,790: Line 3,790:


=={{header|Tailspin}}==
=={{header|Tailspin}}==
<lang tailspin>
<syntaxhighlight lang="tailspin">
def input: ['---------- Ice and Fire ------------',
def input: ['---------- Ice and Fire ------------',
'',
'',
Line 3,810: Line 3,810:
$input... -> '$ -> words -> $(last..first:-1)...;
$input... -> '$ -> words -> $(last..first:-1)...;
' -> !OUT::write
' -> !OUT::write
</syntaxhighlight>
</lang>


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>set lines {
<syntaxhighlight lang="tcl">set lines {
"---------- Ice and Fire ------------"
"---------- Ice and Fire ------------"
""
""
Line 3,829: Line 3,829:
# This would also work for data this simple:
# This would also work for data this simple:
### puts [lreverse $line]
### puts [lreverse $line]
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,845: Line 3,845:
Alternatively…
Alternatively…
{{works with|Tcl|8.6}}
{{works with|Tcl|8.6}}
<lang tcl>puts [join [lmap line $lines {lreverse $line}] "\n"]</lang>
<syntaxhighlight lang="tcl">puts [join [lmap line $lines {lreverse $line}] "\n"]</syntaxhighlight>


=={{header|TXR}}==
=={{header|TXR}}==
Run from command line:
Run from command line:
<lang bash>txr reverse.txr verse.txt</lang>
<syntaxhighlight lang="bash">txr reverse.txr verse.txt</syntaxhighlight>
'''Solution:'''
'''Solution:'''
<lang txr>@(collect)
<syntaxhighlight lang="txr">@(collect)
@ (some)
@ (some)
@(coll)@{words /[^ ]+/}@(end)
@(coll)@{words /[^ ]+/}@(end)
Line 3,864: Line 3,864:
@ (end)
@ (end)
@(end)
@(end)
</syntaxhighlight>
</lang>
New line should be present after the last @(end) terminating vertical definition.
New line should be present after the last @(end) terminating vertical definition.
i.e.
i.e.
<lang txr>@(end)
<syntaxhighlight lang="txr">@(end)
[EOF]</lang>
[EOF]</syntaxhighlight>
not
not
<lang txr>@(end)[EOF]</lang>
<syntaxhighlight lang="txr">@(end)[EOF]</syntaxhighlight>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|bash}}
{{works with|bash}}
<lang bash>while read -a words; do
<syntaxhighlight lang="bash">while read -a words; do
for ((i=${#words[@]}-1; i>=0; i--)); do
for ((i=${#words[@]}-1; i>=0; i--)); do
printf "%s " "${words[i]}"
printf "%s " "${words[i]}"
Line 3,890: Line 3,890:


Frost Robert -----------------------
Frost Robert -----------------------
END</lang>
END</syntaxhighlight>
{{works with|ksh}}
{{works with|ksh}}
Same as above, except change <lang bash>read -a</lang> to <lang bash>read -A</lang>
Same as above, except change <syntaxhighlight lang="bash">read -a</syntaxhighlight> to <syntaxhighlight lang="bash">read -A</syntaxhighlight>


=={{header|VBA}}==
=={{header|VBA}}==
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
Option Explicit


Line 3,933: Line 3,933:
ReverseLine = Join(R, Separat)
ReverseLine = Join(R, Separat)
End If
End If
End Function</lang>
End Function</syntaxhighlight>
{{Out}}
{{Out}}
<pre>------------- Fire And Ice -------------
<pre>------------- Fire And Ice -------------
Line 3,947: Line 3,947:


=={{header|VBScript}}==
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
Option Explicit


Line 3,987: Line 3,987:
objOutFile.Close
objOutFile.Close
Set objFSO = Nothing
Set objFSO = Nothing
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 4,005: Line 4,005:


=={{header|Vlang}}==
=={{header|Vlang}}==
<lang vlang>fn main() {
<syntaxhighlight lang="vlang">fn main() {
mut n := [
mut n := [
"---------- Ice and Fire ------------",
"---------- Ice and Fire ------------",
Line 4,031: Line 4,031:
println(t)
println(t)
}
}
}</lang>
}</syntaxhighlight>




'''Simpler version:'''
'''Simpler version:'''
<lang vlang>mut n := [
<syntaxhighlight lang="vlang">mut n := [
"---------- Ice and Fire ------------",
"---------- Ice and Fire ------------",
" ",
" ",
Line 4,052: Line 4,052:
it.fields().reverse().join(' ').trim_space()
it.fields().reverse().join(' ').trim_space()
).join('\n')
).join('\n')
)</lang>
)</syntaxhighlight>




Line 4,070: Line 4,070:


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>var lines = [
<syntaxhighlight lang="ecmascript">var lines = [
"---------- Ice and Fire ------------",
"---------- Ice and Fire ------------",
" ",
" ",
Line 4,087: Line 4,087:
tokens = tokens[-1..0]
tokens = tokens[-1..0]
System.print(tokens.join(" "))
System.print(tokens.join(" "))
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 4,104: Line 4,104:


=={{header|XBS}}==
=={{header|XBS}}==
<lang XBS>func revWords(x:string=""){
<syntaxhighlight lang="xbs">func revWords(x:string=""){
(x=="")&=>send x+"<br>";
(x=="")&=>send x+"<br>";
set sp = x::split(" ");
set sp = x::split(" ");
Line 4,125: Line 4,125:
foreach(v of lines){
foreach(v of lines){
log(revWords(v));
log(revWords(v));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,141: Line 4,141:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>string 0;
<syntaxhighlight lang="xpl0">string 0;
def LF=$0A, CR=$0D;
def LF=$0A, CR=$0D;


Line 4,181: Line 4,181:
Text(0, Str);
Text(0, Str);
CrLf(0);
CrLf(0);
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 4,198: Line 4,198:


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang Yabasic>data " ---------- Ice and Fire ------------ "
<syntaxhighlight lang="yabasic">data " ---------- Ice and Fire ------------ "
data " "
data " "
data " fire, in end will world the say Some "
data " fire, in end will world the say Some "
Line 4,223: Line 4,223:
break
break
end if
end if
loop</lang>
loop</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>text:=Data(0,String,
<syntaxhighlight lang="zkl">text:=Data(0,String,
#<<<
#<<<
"---------- Ice and Fire ------------
"---------- Ice and Fire ------------
Line 4,242: Line 4,242:
text.pump(11,Data,fcn(s){ // process stripped lines
text.pump(11,Data,fcn(s){ // process stripped lines
s.split(" ").reverse().concat(" ") + "\n" })
s.split(" ").reverse().concat(" ") + "\n" })
.text.print();</lang>
.text.print();</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>