Reverse words in a string: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 45:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">V text =
‘---------- Ice and Fire ------------
 
Line 58:
 
L(line) text.split("\n")
print(reversed(line.split(‘ ’)).join(‘ ’))</langsyntaxhighlight>
 
{{out}}
Line 75:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC Reverse(CHAR ARRAY src,dst)
BYTE i,j,k,beg,end
 
Line 123:
Test("")
Test("Frost Robert -----------------------")
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Reverse_words_in_a_string.png Screenshot from Atari 8-bit computer]
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]].
 
<langsyntaxhighlight Adalang="ada">package Simple_Parse is
-- a very simplistic parser, useful to split a string into words
Line 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 178:
end Next_Word;
end Simple_Parse;</langsyntaxhighlight>
 
===Main Program===
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Simple_Parse;
 
procedure Reverse_Words is
Line 202:
Put_Line(Reverse_Words(Get_Line)); -- poem is read from standard input
end loop;
end Reverse_Words;</langsyntaxhighlight>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">integer j;
list l, x;
text s, t;
Line 227:
}
o_newline();
}</langsyntaxhighlight>
{{out}}
<pre>------------ Fire and Ice ----------
Line 241:
 
=={{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 284:
print( ( reverse word order ( " " ), newline ) );
print( ( reverse word order ( "Frost Robert -----------------------" ), newline ) )
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 301:
=={{header|AppleScript}}==
 
<langsyntaxhighlight AppleScriptlang="applescript">on run
 
unlines(map(reverseWords, |lines|("---------- Ice and Fire ------------
Line 392:
end if
end mReturn
</syntaxhighlight>
</lang>
{{out}}
 
Line 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 433:
350 IF C$ <> " " THEN W$ = C$ + W$ : NEXT I
360 RETURN
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">text: {
---------- Ice and Fire ------------
Line 451:
[join.with:" " reverse split.words &]
 
print join.with:"\n" reversed</langsyntaxhighlight>
 
{{out}}
Line 467:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Data := "
(Join`r`n
---------- Ice and Fire ------------
Line 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 513:
exit(0)
}
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 529:
 
=={{header|BaCon}}==
<langsyntaxhighlight lang="qbasic">
PRINT REV$("---------- Ice and Fire ------------")
PRINT
Line 540:
PRINT
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).
{{out}}
Line 557:
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">@echo off
 
::The Main Thing...
Line 591:
echo.%reversed%
goto :EOF
::/The Function...</langsyntaxhighlight>
{{Out}}
<pre>
Line 609:
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight BASIC256lang="basic256">source = freefile
open (source, "m:\text.txt")
textEnt$ = ""
Line 624:
print textSal$[n];
next n
close source</langsyntaxhighlight>
 
=={{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 643:
LOCAL sp%
sp%=INSTR(s$," ")
IF sp% THEN =FNreverse(MID$(s$,sp%+1))+" "+LEFT$(s$,sp%-1) ELSE =s$</langsyntaxhighlight>
 
{{out}}
Line 658:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">("---------- Ice and Fire ------------
fire, in end will world the say Some
Line 694:
& !output reverse$!text:?output
& out$str$!output
);</langsyntaxhighlight>
{{out}}
<pre>------------ Fire and Ice ----------
Line 708:
 
=={{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 750:
 
return 0;
}</langsyntaxhighlight>
Output is the same as everyone else's.
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
 
public class ReverseWordsInString
Line 780:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <algorithm>
#include <functional>
Line 844:
return 0;
}
</syntaxhighlight>
</lang>
 
===Alternate version===
<langsyntaxhighlight lang="cpp">
#include <string>
#include <iostream>
Line 888:
return system( "pause" );
}
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">
(def poem
"---------- Ice and Fire ------------
Line 906:
(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 973:
.
end program rev-word.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 990:
=={{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 1,001:
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 1,034:
(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 1,056:
writefln("%(%-(%s %)\n%)",
text.splitLines.map!(r => r.split.retro));
}</langsyntaxhighlight>
The output is the same as the Python entry.
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program RosettaCode_ReverseWordsInAString;
 
{$APPTYPE CONSOLE}
Line 1,097:
end;
ReadLn;
end.</langsyntaxhighlight>
The output is the same as the Pascal entry.
 
=={{header|EchoLisp}}==
Using a here-string input :
<langsyntaxhighlight lang="scheme">
(define S #<<
---------- Ice and Fire ------------
Line 1,119:
(for/list ((line (string-split S "\n")))
(string-join (reverse (string-split line " ")) " ")))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,136:
=={{header|Elena}}==
ELENA 5.0:
<langsyntaxhighlight lang="elena">import extensions;
import system'routines;
Line 1,160:
console.writeLine()
}
}</langsyntaxhighlight>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule RC do
def reverse_words(txt) do
txt |> String.split("\n") # split lines
Line 1,172:
|> Enum.join("\n") # rejoin lines
end
end</langsyntaxhighlight>
Usage:
<langsyntaxhighlight lang="elixir">txt = """
---------- Ice and Fire ------------
Line 1,187:
"""
 
IO.puts RC.reverse_words(txt)</langsyntaxhighlight>
 
=={{header|Elm}}==
 
<langsyntaxhighlight lang="elm">
reversedPoem =
String.trim """
Line 1,214:
poem =
reverseLinesWords reversedPoem
</syntaxhighlight>
</lang>
 
=={{header|Emacs Lisp}}==
 
<langsyntaxhighlight Lisplang="lisp">(defun reverse-words (line)
(insert
(format "%s\n"
Line 1,236:
"... elided paragraph last ..."
""
"Frost Robert ----------------------- "))</langsyntaxhighlight>
 
{{out}}
Line 1,254:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
//Reverse words in a string. Nigel Galloway: July 14th., 2021
[" ---------- Ice and Fire ------------ ";
Line 1,266:
" ";
" Frost Robert ----------------------- "]|>List.map(fun n->n.Split " "|>Array.filter((<>)"")|>Array.rev|>String.concat " ")|>List.iter(printfn "%s")
</langsyntaxhighlight>
{{out}}
<pre>
Line 1,281:
</pre>
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: io sequences splitting ;
IN: rosetta-code.reverse-words
 
Line 1,295:
Frost Robert -----------------------"
 
"\n" split [ " " split reverse " " join ] map [ print ] each</langsyntaxhighlight>
{{out}}
<pre>
Line 1,312:
=={{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 ;
Line 1,325:
reverse ... elided paragraph last ...
reverse
reverse Frost Robert -----------------------</langsyntaxhighlight>
 
'''Output'''
Line 1,346:
Fortran syntax is mostly Fortran 77.
 
<langsyntaxhighlight lang="fortran">
character*40 words
character*40 reversed
Line 1,375:
end
 
</syntaxhighlight>
</lang>
 
Output from comand: <b>cat frostPoem.txt | reverse</b><p>
Line 1,396:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Sub split (s As String, sepList As String, result() As String, removeEmpty As Boolean = False)
Line 1,447:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,456:
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">
lines=split["\n",
"""---------- Ice and Fire ------------
Line 1,471:
for line = lines
println[join[" ", reverse[split[%r/\s+/, line]]]]
</syntaxhighlight>
</lang>
 
=={{header|FutureBasic}}==
<langsyntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
Line 1,507:
 
HandleEvents
</syntaxhighlight>
</lang>
 
Output:
Line 1,525:
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=c81c1bbf94e856035fd382015d208272 Click this link to run this code]'''
<langsyntaxhighlight 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
Line 1,560:
Print sOutput 'Print the output
 
End</langsyntaxhighlight>
Output:
<pre>
Line 1,576:
 
=={{header|Gema}}==
<langsyntaxhighlight lang="gema">\L<G> <U>=@{$2} $1</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,614:
fmt.Println(t)
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,630:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def text = new StringBuilder()
.append('---------- Ice and Fire ------------\n')
.append(' \n')
Line 1,644:
text.eachLine { line ->
println "$line --> ${line.split(' ').reverse().join(' ')}"
}</langsyntaxhighlight>
{{output}}
<pre>---------- Ice and Fire ------------ --> ------------ Fire and Ice ----------
Line 1,658:
 
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">
<lang Haskell>
revstr :: String -> String
revstr = unwords . reverse . words -- point-free style
Line 1,677:
\\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,684:
 
Works in both languages:
<langsyntaxhighlight lang="unicon">procedure main()
every write(rWords(&input))
end
Line 1,697:
procedure genWords()
while w := 1(tab(upto(" \t")),tab(many(" \t"))) || " " do suspend w
end</langsyntaxhighlight>
 
{{out}} for test file:
Line 1,719:
Treated interactively:
 
<langsyntaxhighlight Jlang="j"> ([:;@|.[:<;.1 ' ',]);._2]0 :0
---------- Ice and Fire ------------
 
Line 1,741:
----------------------- 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.
Line 1,747:
Another approach:
 
<langsyntaxhighlight Jlang="j">echo ;:inv@|.@cut;._2 {{)n
---------- Ice and Fire ------------
Line 1,758:
Frost Robert -----------------------
}}</langsyntaxhighlight>
 
produces:
Line 1,776:
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public class ReverseWords {
 
static final String[] lines = {
Line 1,797:
}
}
}</langsyntaxhighlight>
{{works with|Java|8+}}
<langsyntaxhighlight lang="java">package string;
 
import static java.util.Arrays.stream;
Line 1,837:
;
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,853:
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">var strReversed =
"---------- Ice and Fire ------------\n\
\n\
Line 1,875:
console.log(
reverseString(strReversed)
);</langsyntaxhighlight>
 
Output:
Line 1,890:
 
=={{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,903:
... last paragraph elided ...
 
----------------------- Robert Frost</langsyntaxhighlight>
 
=={{header|Jsish}}==
From Javascript entry.
<langsyntaxhighlight lang="javascript">var strReversed =
"---------- Ice and Fire ------------\n
fire, in end will world the say Some
Line 1,952:
----------------------- Robert Frost
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 1,960:
 
=={{header|Julia}}==
<langsyntaxhighlight Julialang="julia">revstring (str) = join(reverse(split(str, " ")), " ")</langsyntaxhighlight>{{Out}}
<pre>julia> revstring("Hey you, Bub!")
"Bub! you, Hey"
Line 1,991:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="kotlin">fun reversedWords(s: String) = s.split(" ").filter { it.isNotEmpty() }.reversed().joinToString(" ")
 
fun main() {
Line 2,010:
)
sl.forEach { println(reversedWords(it)) }
}</langsyntaxhighlight>
 
{{out}}
Line 2,029:
 
=={{header|Ksh}}==
<langsyntaxhighlight lang="ksh">
#!/bin/ksh
 
Line 2,059:
... elided paragraph last ...
Frost Robert -----------------------
EOF</langsyntaxhighlight>
{{out}}<pre>
------------ Fire and Ice ----------
Line 2,073:
=={{header|Lambdatalk}}==
This answer illustrates how a missing primitive (line_split) can be added directly in the wiki page.
<langsyntaxhighlight lang="scheme">
1) We write a function
 
Line 2,142:
----------------------- Robert Frost
</syntaxhighlight>
</lang>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
for i = 1 to 10
read string$
Line 2,172:
data ""
data "Frost Robert -----------------------"
</syntaxhighlight>
</lang>
{{Out}}
<pre>------------ Fire and Ice ----------
Line 2,187:
=={{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 2,193:
put cr after txtrev -- preserve line
end repeat
put txtrev</langsyntaxhighlight>
 
=={{header|LiveScript}}==
<langsyntaxhighlight lang="livescript">
poem =
"""
Line 2,214:
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 2,252:
See below for original entry and the input string under variable 's'. Here is a significantly shorter program.
 
<langsyntaxhighlight lang="lua">
local lines = {}
for line in (s .. "\n"):gmatch("(.-)\n") do
Line 2,262:
end
print(table.concat(lines, "\n"))
</syntaxhighlight>
</lang>
 
 
Line 2,282:
]]
 
<langsyntaxhighlight lang="lua">function table.reverse(a)
local res = {}
for i = #a, 1, -1 do
Line 2,300:
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|Maple}}==
<langsyntaxhighlight Maplelang="maple">while (true) do
input := readline("input.txt"):
if input = 0 then break: fi:
Line 2,311:
input := StringTools:-Join(ListTools:-Reverse(StringTools:-Split(input, " "))," "):
printf("%s\n", input):
od:</langsyntaxhighlight>
{{Out|Output}}
<pre>------------ Fire and Ice ----------
Line 2,325:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">poem = "---------- Ice and Fire ------------
fire, in end will world the say Some
Line 2,340:
linesWithReversedWords =
StringJoin[Riffle[#, " "]] & /@ reversedWordArray;
finaloutput = StringJoin[Riffle[#, "\n"]] & @ linesWithReversedWords</langsyntaxhighlight>
{{out}}
<pre>------------ Fire and Ice ----------
Line 2,354:
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight MATLABlang="matlab">function testReverseWords
testStr = {'---------- Ice and Fire ------------' ; ...
'' ; ...
Line 2,378:
strOut = strtrim(sprintf('%s ', words{end:-1:1}));
end
end</langsyntaxhighlight>
{{out}}
<pre>------------ Fire and Ice ----------
Line 2,392:
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang="maxscript">
-- MAXScript : Reverse words in a string : N.H. 2019
--
Line 2,418:
) -- end of while eof
)
</syntaxhighlight>
</lang>
{{out}}
Output to MAXScript Listener:
Line 2,433:
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">lines = ["==========================================",
"| ---------- Ice and Fire ------------ |",
"| |",
Line 2,457:
end while
print newLine.join
end for</langsyntaxhighlight>
{{out}}
<pre>
Line 2,477:
{{trans|Pascal}}
{{works with|ADW Modula-2|any (Compile with the linker option ''Console Application'').}}
<langsyntaxhighlight lang="modula2">
MODULE ReverseWords;
 
Line 2,536:
END;
END ReverseWords.
</syntaxhighlight>
</lang>
 
=={{header|Nanoquery}}==
<langsyntaxhighlight lang="nanoquery">def reverse_words(string)
tokens = split(string, " ")
if len(tokens) = 0
Line 2,564:
for line in split(data, "\n")
println reverse_words(line)
end</langsyntaxhighlight>
{{out}}
<pre>------------ Fire and Ice ----------
Line 2,580:
{{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.
join is rest link (' ' eachboth link)
Line 2,599:
'' \
'Poe Edgar -----------------------'
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,618:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import strutils
 
let text = """---------- Ice and Fire ------------
Line 2,644:
 
for line in text.splitLines():
echo line.split(' ').reversed().join(" ")</langsyntaxhighlight>
{{out}}
<pre>------------ Fire and Ice ----------
Line 2,658:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">use Collection;
 
class Reverselines {
Line 2,686:
};
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,701:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">#load "str.cma"
let input = ["---------- Ice and Fire ------------";
"";
Line 2,716:
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 2,733:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: revWords(s)
s words reverse unwords ;
 
Line 2,746:
"... elided paragraph last ... " revWords println
" " revWords println
"Frost Robert -----------------------" revWords println ;</langsyntaxhighlight>
 
{{out}}
Line 2,766:
=={{header|Pascal}}==
Free Pascal 3.0.0
<langsyntaxhighlight lang="pascal">program Reverse_words(Output);
{$H+}
 
Line 2,811:
end;
readln;
end.</langsyntaxhighlight>
{{out}}
<pre>----------- Fire and Ice ----------
Line 2,825:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">print join(" ", reverse split), "\n" for <DATA>;
__DATA__
---------- Ice and Fire ------------
Line 2,837:
Frost Robert -----------------------
</syntaxhighlight>
</lang>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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;">"""
Line 2,859:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,875:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
"---------- Ice and Fire ------------"
Line 2,897:
else drop endif
drop nl
endfor</langsyntaxhighlight>
{{out}}
<pre>
Line 2,913:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">
<?php
Line 2,941:
 
 
echo strInv($string);</langsyntaxhighlight>
'''Output''':
 
<langsyntaxhighlight Shelllang="shell">------------ Fire and Ice ----------
 
Some say the world will end in fire,
Line 2,953:
... last paragraph elided ...
 
----------------------- Robert Frost</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight Pikelang="pike">string story = #"---------- Ice and Fire ------------
fire, in end will world the say Some
Line 2,978:
foreach(story/"\n", string line)
write("%s\n", reverse(line/" ")*" ");
</syntaxhighlight>
</lang>
 
=={{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 3,013:
put edit ('---> ', reverse) (col(40), 2 A);
end;
end rev;</langsyntaxhighlight>
{{out}}
<pre>
Line 3,030:
=={{header|PowerShell}}==
{{works with|PowerShell|4.0}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
Function Reverse-Words($lines) {
$lines | foreach {
Line 3,051:
 
Reverse-Words($lines)
</syntaxhighlight>
</lang>
 
'''output''' :
Line 3,068:
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang="purebasic">a$ = "---------- Ice and Fire ------------" +#CRLF$+
" " +#CRLF$+
"fire, in end will world the say Some" +#CRLF$+
Line 3,089:
Next
Input()
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,107:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python"> text = '''\
---------- Ice and Fire ------------
 
Line 3,119:
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 3,132:
... last paragraph elided ...
 
----------------------- Robert Frost</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> ' [ $ " ---------- Ice and Fire ------------ "
$ ""
$ " fire, in end will world the say Some "
Line 3,151:
witheach
[ echo$ sp ]
cr ]</langsyntaxhighlight>
 
{{out}}
Line 3,168:
=={{header|R}}==
 
<syntaxhighlight lang="r">
<lang R>
whack <- function(s) {
paste( rev( unlist(strsplit(s, " "))), collapse=' ' ) }
Line 3,187:
 
for (line in poem) cat( whack(line), "\n" )
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,208:
(Everything that happens in R is a function-call.)
 
<syntaxhighlight lang="r">
<lang R>
> `{` <- function(s) rev(unlist(strsplit(s, " ")))
> {"one two three four five"}
[1] "five" "four" "three" "two" "one"
</syntaxhighlight>
</lang>
 
You had better restart your REPL after trying this.
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket/base
 
(require racket/string)
Line 3,244:
(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):
<langsyntaxhighlight lang="racket">
#lang sweet-exp racket/base
require racket/string
Line 3,276:
displayln split-reverse(l)
loop read-line(poem-port)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
We'll read input from stdin
<syntaxhighlight lang="raku" perl6line>say ~.words.reverse for lines</langsyntaxhighlight>
{{out}}
<pre>------------ Fire and Ice ----------
Line 3,295:
 
=={{header|Red}}==
<langsyntaxhighlight Redlang="red">Red []
foreach line
split
Line 3,310:
print reverse split line " "
]
</syntaxhighlight>
</lang>
 
=={{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 3,334:
 
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 3,351:
===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 3,370:
 
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 3,392:
for y in aList2 see y + " " next see nl
next
</syntaxhighlight>
</lang>
 
Output
<langsyntaxhighlight lang="ring">
------------ Fire and Ice ----------
 
Line 3,405:
... last paragraph elided ...
----------------------- Robert Frost
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">puts <<EOS
---------- Ice and Fire ------------
 
Line 3,420:
Frost Robert -----------------------
EOS
.each_line.map {|line| line.split.reverse.join(' ')}</langsyntaxhighlight>
 
Output the same as everyone else's.
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">for i = 1 to 10
read string$
j = 1
Line 3,446:
data "... elided paragraph last ..."
data ""
data "Frost Robert -----------------------"</langsyntaxhighlight>
Output:
<pre>------------ Fire and Ice ----------
Line 3,460:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">const TEXT: &'static str =
"---------- Ice and Fire ------------
Line 3,482:
.collect::<Vec<_>>() // Collect lines into Vec<String>
.join("\n")); // Concatenate lines into String
}</langsyntaxhighlight>
 
=={{header|S-lang}}==
<langsyntaxhighlight Slang="s-lang">variable ln, in =
["---------- Ice and Fire ------------",
"fire, in end will world the say Some",
Line 3,500:
array_reverse(ln);
() = printf("%s\n", strjoin(ln, " "));
}</langsyntaxhighlight>
{{out}}
<pre>------------ Fire and Ice ----------
Line 3,515:
{{works with|Scala|2.9.x}}
 
<langsyntaxhighlight Scalalang="scala">object ReverseWords extends App {
 
"""| ---------- Ice and Fire ------------
Line 3,531:
.foreach{println}
}</langsyntaxhighlight>
 
{{out}}
Line 3,550:
{{works with|Gauche Scheme}}
 
<syntaxhighlight lang="scheme">
<lang Scheme>
(for-each
(lambda (s) (print (string-join (reverse (string-split s #/ +/)))))
Line 3,565:
Frost Robert -----------------------"
#/[ \r]*\n[ \r]*/))
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 3,581:
 
=={{header|sed}}==
<langsyntaxhighlight lang="sed">#!/usr/bin/sed -f
 
G
Line 3,587:
s/^[[:space:]]*\([^[:space:]][^[:space:]]*\)\(.*\n\)/\2 \1/
t loop
s/^[[:space:]]*//</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const array string: lines is [] (
Line 3,617:
writeln;
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 3,634:
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang="sensetalk">set poem to {{
---------- Ice and Fire ------------
 
Line 3,650:
put (each word of it) reversed joined by space
end repeat
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,666:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">DATA.each{|line| line.words.reverse.join(" ").say};
 
__DATA__
Line 3,678:
... elided paragraph last ...
 
Frost Robert -----------------------</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="smalltalk">
poem := '---------- Ice and Fire ------------
Line 3,694:
 
(poem lines collect: [ :line | ((line splitOn: ' ') reverse) joinUsing: ' ' ]) joinUsing: (String cr).
</syntaxhighlight>
</lang>
 
{{out}}
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.)
 
<langsyntaxhighlight lang="sparkling">let lines = split("---------- Ice and Fire ------------
 
fire, in end will world the say Some
Line 3,733:
 
print();
});</langsyntaxhighlight>
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">val lines = [
" ---------- Ice and Fire ------------ ",
" ",
Line 3,751:
val revWords = String.concatWith " " o rev o String.tokens Char.isSpace
 
val () = app (fn line => print (revWords line ^ "\n")) lines</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">import Foundation
 
// convenience extension for better clarity
Line 3,774:
let output = input.lines.map { $0.words.reverse().joinWithSeparator(" ") }.joinWithSeparator("\n")
 
print(output)</langsyntaxhighlight>
{{out}}
<pre>
Line 3,790:
 
=={{header|Tailspin}}==
<langsyntaxhighlight lang="tailspin">
def input: ['---------- Ice and Fire ------------',
'',
Line 3,810:
$input... -> '$ -> words -> $(last..first:-1)...;
' -> !OUT::write
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">set lines {
"---------- Ice and Fire ------------"
""
Line 3,829:
# This would also work for data this simple:
### puts [lreverse $line]
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,845:
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 3,864:
@ (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 3,890:
 
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">
<lang vb>
Option Explicit
 
Line 3,933:
ReverseLine = Join(R, Separat)
End If
End Function</langsyntaxhighlight>
{{Out}}
<pre>------------- Fire And Ice -------------
Line 3,947:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
 
Line 3,987:
objOutFile.Close
Set objFSO = Nothing
</syntaxhighlight>
</lang>
 
{{Out}}
Line 4,005:
 
=={{header|Vlang}}==
<langsyntaxhighlight lang="vlang">fn main() {
mut n := [
"---------- Ice and Fire ------------",
Line 4,031:
println(t)
}
}</langsyntaxhighlight>
 
 
'''Simpler version:'''
<langsyntaxhighlight lang="vlang">mut n := [
"---------- Ice and Fire ------------",
" ",
Line 4,052:
it.fields().reverse().join(' ').trim_space()
).join('\n')
)</langsyntaxhighlight>
 
 
Line 4,070:
 
=={{header|Wren}}==
<langsyntaxhighlight lang="ecmascript">var lines = [
"---------- Ice and Fire ------------",
" ",
Line 4,087:
tokens = tokens[-1..0]
System.print(tokens.join(" "))
}</langsyntaxhighlight>
 
{{out}}
Line 4,104:
 
=={{header|XBS}}==
<langsyntaxhighlight XBSlang="xbs">func revWords(x:string=""){
(x=="")&=>send x+"<br>";
set sp = x::split(" ");
Line 4,125:
foreach(v of lines){
log(revWords(v));
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,141:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">string 0;
def LF=$0A, CR=$0D;
 
Line 4,181:
Text(0, Str);
CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 4,198:
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">data " ---------- Ice and Fire ------------ "
data " "
data " fire, in end will world the say Some "
Line 4,223:
break
end if
loop</langsyntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">text:=Data(0,String,
#<<<
"---------- Ice and Fire ------------
Line 4,242:
text.pump(11,Data,fcn(s){ // process stripped lines
s.split(" ").reverse().concat(" ") + "\n" })
.text.print();</langsyntaxhighlight>
{{out}}
<pre>
10,327

edits