Reverse words in a string: Difference between revisions
m
syntax highlighting fixup automation
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 45:
{{trans|Python}}
<
‘---------- Ice and Fire ------------
Line 58:
L(line) text.split("\n")
print(reversed(line.split(‘ ’)).join(‘ ’))</
{{out}}
Line 75:
=={{header|Action!}}==
<
BYTE i,j,k,beg,end
Line 123:
Test("")
Test("Frost Robert -----------------------")
RETURN</
{{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]].
<
-- 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;</
The implementation of "Simple_Parse":
<
function Next_Word(S: String; Point: in out Positive) return String is
Line 178:
end Next_Word;
end Simple_Parse;</
===Main Program===
<
procedure Reverse_Words is
Line 202:
Put_Line(Reverse_Words(Get_Line)); -- poem is read from standard input
end loop;
end Reverse_Words;</
=={{header|Aime}}==
<
list l, x;
text s, t;
Line 227:
}
o_newline();
}</
{{out}}
<pre>------------ Fire and Ice ----------
Line 241:
=={{header|ALGOL 68}}==
<
# 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>
{{out}}
<pre>
Line 301:
=={{header|AppleScript}}==
<
unlines(map(reverseWords, |lines|("---------- Ice and Fire ------------
Line 392:
end if
end mReturn
</syntaxhighlight>
{{out}}
Line 407:
=={{header|Applesoft BASIC}}==
<
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>
=={{header|Arturo}}==
<
---------- Ice and Fire ------------
Line 451:
[join.with:" " reverse split.words &]
print join.with:"\n" reversed</
{{out}}
Line 467:
=={{header|AutoHotkey}}==
<
(Join`r`n
---------- Ice and Fire ------------
Line 487:
Output .= Line "`n", Line := ""
}
MsgBox, % RTrim(Output, "`n")</
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f REVERSE_WORDS_IN_A_STRING.AWK
BEGIN {
Line 513:
exit(0)
}
</syntaxhighlight>
{{Output}}
<pre>
Line 529:
=={{header|BaCon}}==
<
PRINT REV$("---------- Ice and Fire ------------")
PRINT
Line 540:
PRINT
PRINT REV$("Frost Robert -----------------------")
</syntaxhighlight>
Using the REV$ function which takes a sentence as a delimited string where the items are separated by a delimiter (the space character is the default delimiter).
{{out}}
Line 557:
=={{header|Batch File}}==
<
::The Main Thing...
Line 591:
echo.%reversed%
goto :EOF
::/The Function...</
{{Out}}
<pre>
Line 609:
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<
open (source, "m:\text.txt")
textEnt$ = ""
Line 624:
print textSal$[n];
next n
close source</
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
\ '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$</
{{out}}
Line 658:
=={{header|Bracmat}}==
<
fire, in end will world the say Some
Line 694:
& !output reverse$!text:?output
& out$str$!output
);</
{{out}}
<pre>------------ Fire and Ice ----------
Line 708:
=={{header|Burlesque}}==
<
blsq ) "It is not raining"wd<-wd
"raining not is It"
blsq ) "ice. in say some"wd<-wd
"some say in ice."
</syntaxhighlight>
=={{header|C}}==
<
#include <ctype.h>
Line 750:
return 0;
}</
Output is the same as everyone else's.
=={{header|C sharp|C#}}==
<
public class ReverseWordsInString
Line 780:
}
}
}</
=={{header|C++}}==
<
#include <algorithm>
#include <functional>
Line 844:
return 0;
}
</syntaxhighlight>
===Alternate version===
<
#include <string>
#include <iostream>
Line 888:
return system( "pause" );
}
</syntaxhighlight>
=={{header|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>
Output is the same as everyone else's.
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
program-id. rev-word.
data division.
Line 973:
.
end program rev-word.
</syntaxhighlight>
{{out}}
<pre>
Line 990:
=={{header|CoffeeScript}}==
{{trans|JavaScript}}
<
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)</
{{out}}
As JavaScript.
=={{header|Common Lisp}}==
<
(labels
((iter (s lst)
Line 1,034:
(loop for line = (read-line s NIL)
while line
do (format t "~{~a~#[~:; ~]~}~%" (split-and-reverse line))))</
Output is the same as everyone else's.
=={{header|D}}==
<
import std.stdio, std.string, std.range, std.algorithm;
Line 1,056:
writefln("%(%-(%s %)\n%)",
text.splitLines.map!(r => r.split.retro));
}</
The output is the same as the Python entry.
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 1,097:
end;
ReadLn;
end.</
The output is the same as the Pascal entry.
=={{header|EchoLisp}}==
Using a here-string input :
<
(define S #<<
---------- Ice and Fire ------------
Line 1,119:
(for/list ((line (string-split S "\n")))
(string-join (reverse (string-split line " ")) " ")))
</syntaxhighlight>
{{out}}
<pre>
Line 1,136:
=={{header|Elena}}==
ELENA 5.0:
<
import system'routines;
Line 1,160:
console.writeLine()
}
}</
=={{header|Elixir}}==
<
def reverse_words(txt) do
txt |> String.split("\n") # split lines
Line 1,172:
|> Enum.join("\n") # rejoin lines
end
end</
Usage:
<
---------- Ice and Fire ------------
Line 1,187:
"""
IO.puts RC.reverse_words(txt)</
=={{header|Elm}}==
<
reversedPoem =
String.trim """
Line 1,214:
poem =
reverseLinesWords reversedPoem
</syntaxhighlight>
=={{header|Emacs Lisp}}==
<
(insert
(format "%s\n"
Line 1,236:
"... elided paragraph last ..."
""
"Frost Robert ----------------------- "))</
{{out}}
Line 1,254:
=={{header|F_Sharp|F#}}==
<
//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")
</
{{out}}
<pre>
Line 1,281:
</pre>
=={{header|Factor}}==
<
IN: rosetta-code.reverse-words
Line 1,295:
Frost Robert -----------------------"
"\n" split [ " " split reverse " " join ] map [ print ] each</
{{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 -----------------------</
'''Output'''
Line 1,346:
Fortran syntax is mostly Fortran 77.
<
character*40 words
character*40 reversed
Line 1,375:
end
</syntaxhighlight>
Output from comand: <b>cat frostPoem.txt | reverse</b><p>
Line 1,396:
=={{header|FreeBASIC}}==
<
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</
{{out}}
Line 1,456:
=={{header|Frink}}==
<
lines=split["\n",
"""---------- Ice and Fire ------------
Line 1,471:
for line = lines
println[join[" ", reverse[split[%r/\s+/, line]]]]
</syntaxhighlight>
=={{header|FutureBasic}}==
<
include "NSLog.incl"
Line 1,507:
HandleEvents
</syntaxhighlight>
Output:
Line 1,525:
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=c81c1bbf94e856035fd382015d208272 Click this link to run this code]'''
<
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</
Output:
<pre>
Line 1,576:
=={{header|Gema}}==
<
=={{header|Go}}==
<
import (
Line 1,614:
fmt.Println(t)
}
}</
{{out}}
<pre>
Line 1,630:
=={{header|Groovy}}==
<
.append('---------- Ice and Fire ------------\n')
.append(' \n')
Line 1,644:
text.eachLine { line ->
println "$line --> ${line.split(' ').reverse().join(' ')}"
}</
{{output}}
<pre>---------- Ice and Fire ------------ --> ------------ Fire and Ice ----------
Line 1,658:
=={{header|Haskell}}==
<syntaxhighlight 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>
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:
<
every write(rWords(&input))
end
Line 1,697:
procedure genWords()
while w := 1(tab(upto(" \t")),tab(many(" \t"))) || " " do suspend w
end</
{{out}} for test file:
Line 1,719:
Treated interactively:
<
---------- Ice and Fire ------------
Line 1,741:
----------------------- Robert Frost
</syntaxhighlight>
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:
<
---------- Ice and Fire ------------
Line 1,758:
Frost Robert -----------------------
}}</
produces:
Line 1,776:
=={{header|Java}}==
<
static final String[] lines = {
Line 1,797:
}
}
}</
{{works with|Java|8+}}
<
import static java.util.Arrays.stream;
Line 1,837:
;
}
}</
{{out}}
Line 1,853:
=={{header|JavaScript}}==
<
"---------- Ice and Fire ------------\n\
\n\
Line 1,875:
console.log(
reverseString(strReversed)
);</
Output:
Line 1,890:
=={{header|jq}}==
<
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.<
------------ Fire and Ice ----------
Line 1,903:
... last paragraph elided ...
----------------------- Robert Frost</
=={{header|Jsish}}==
From Javascript entry.
<
"---------- Ice and Fire ------------\n
fire, in end will world the say Some
Line 1,952:
----------------------- Robert Frost
=!EXPECTEND!=
*/</
{{out}}
Line 1,960:
=={{header|Julia}}==
<
<pre>julia> revstring("Hey you, Bub!")
"Bub! you, Hey"
Line 1,991:
=={{header|Kotlin}}==
<
fun main() {
Line 2,010:
)
sl.forEach { println(reversedWords(it)) }
}</
{{out}}
Line 2,029:
=={{header|Ksh}}==
<
#!/bin/ksh
Line 2,059:
... elided paragraph last ...
Frost Robert -----------------------
EOF</
{{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.
<
1) We write a function
Line 2,142:
----------------------- Robert Frost
</syntaxhighlight>
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
for i = 1 to 10
read string$
Line 2,172:
data ""
data "Frost Robert -----------------------"
</syntaxhighlight>
{{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
<
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</
=={{header|LiveScript}}==
<
poem =
"""
Line 2,214:
reverse-string = (.split '\n') >> (.map reverse-words) >> (.join '\n')
reverse-string poem
</syntaxhighlight>
=={{header|Logo}}==
This version just reads the words from standard input.
<
make "line readlist
print reverse :line
] [word? :line]
bye</
{{Out}}
Line 2,252:
See below for original entry and the input string under variable 's'. Here is a significantly shorter program.
<
local lines = {}
for line in (s .. "\n"):gmatch("(.-)\n") do
Line 2,262:
end
print(table.concat(lines, "\n"))
</syntaxhighlight>
Line 2,282:
]]
<
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</
''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}}==
<
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:</
{{Out|Output}}
<pre>------------ Fire and Ice ----------
Line 2,325:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
fire, in end will world the say Some
Line 2,340:
linesWithReversedWords =
StringJoin[Riffle[#, " "]] & /@ reversedWordArray;
finaloutput = StringJoin[Riffle[#, "\n"]] & @ linesWithReversedWords</
{{out}}
<pre>------------ Fire and Ice ----------
Line 2,354:
=={{header|MATLAB}} / {{header|Octave}}==
<
testStr = {'---------- Ice and Fire ------------' ; ...
'' ; ...
Line 2,378:
strOut = strtrim(sprintf('%s ', words{end:-1:1}));
end
end</
{{out}}
<pre>------------ Fire and Ice ----------
Line 2,392:
=={{header|MAXScript}}==
<
-- MAXScript : Reverse words in a string : N.H. 2019
--
Line 2,418:
) -- end of while eof
)
</syntaxhighlight>
{{out}}
Output to MAXScript Listener:
Line 2,433:
=={{header|MiniScript}}==
<
"| ---------- Ice and Fire ------------ |",
"| |",
Line 2,457:
end while
print newLine.join
end for</
{{out}}
<pre>
Line 2,477:
{{trans|Pascal}}
{{works with|ADW Modula-2|any (Compile with the linker option ''Console Application'').}}
<
MODULE ReverseWords;
Line 2,536:
END;
END ReverseWords.
</syntaxhighlight>
=={{header|Nanoquery}}==
<
tokens = split(string, " ")
if len(tokens) = 0
Line 2,564:
for line in split(data, "\n")
println reverse_words(line)
end</
{{out}}
<pre>------------ Fire and Ice ----------
Line 2,580:
{{works with|Q'Nial Version 6.3}}
<syntaxhighlight lang="nial">
# Define a function to convert a list of strings to a single string.
join is rest link (' ' eachboth link)
Line 2,599:
'' \
'Poe Edgar -----------------------'
</syntaxhighlight>
{{out}}
Line 2,618:
=={{header|Nim}}==
<
let text = """---------- Ice and Fire ------------
Line 2,644:
for line in text.splitLines():
echo line.split(' ').reversed().join(" ")</
{{out}}
<pre>------------ Fire and Ice ----------
Line 2,658:
=={{header|Objeck}}==
<
class Reverselines {
Line 2,686:
};
}
}</
{{out}}
Line 2,701:
=={{header|OCaml}}==
<
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;;</
Sample usage
<pre>$ ocaml reverse.ml
Line 2,733:
=={{header|Oforth}}==
<
s words reverse unwords ;
Line 2,746:
"... elided paragraph last ... " revWords println
" " revWords println
"Frost Robert -----------------------" revWords println ;</
{{out}}
Line 2,766:
=={{header|Pascal}}==
Free Pascal 3.0.0
<
{$H+}
Line 2,811:
end;
readln;
end.</
{{out}}
<pre>----------- Fire and Ice ----------
Line 2,825:
=={{header|Perl}}==
<
__DATA__
---------- Ice and Fire ------------
Line 2,837:
Frost Robert -----------------------
</syntaxhighlight>
=={{header|Phix}}==
<!--<
<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>
<!--</
{{out}}
<pre>
Line 2,875:
=={{header|Phixmonti}}==
<
"---------- Ice and Fire ------------"
Line 2,897:
else drop endif
drop nl
endfor</
{{out}}
<pre>
Line 2,913:
=={{header|PHP}}==
<
<?php
Line 2,941:
echo strInv($string);</
'''Output''':
<
Some say the world will end in fire,
Line 2,953:
... last paragraph elided ...
----------------------- Robert Frost</
=={{header|PicoLisp}}==
<syntaxhighlight lang="picolisp">
(in "FireIce.txt"
(until (eof)
(prinl (glue " " (flip (split (line) " "))))))
</syntaxhighlight>
{{Out}}
Same as anybody else.
=={{header|Pike}}==
<
fire, in end will world the say Some
Line 2,978:
foreach(story/"\n", string line)
write("%s\n", reverse(line/" ")*" ");
</syntaxhighlight>
=={{header|PL/I}}==
<
declare (s, reverse) character (50) varying;
declare (i, j) fixed binary;
Line 3,013:
put edit ('---> ', reverse) (col(40), 2 A);
end;
end rev;</
{{out}}
<pre>
Line 3,030:
=={{header|PowerShell}}==
{{works with|PowerShell|4.0}}
<syntaxhighlight lang="powershell">
Function Reverse-Words($lines) {
$lines | foreach {
Line 3,051:
Reverse-Words($lines)
</syntaxhighlight>
'''output''' :
Line 3,068:
=={{header|PureBasic}}==
<
" " +#CRLF$+
"fire, in end will world the say Some" +#CRLF$+
Line 3,089:
Next
Input()
</syntaxhighlight>
{{out}}
<pre>
Line 3,107:
=={{header|Python}}==
<
---------- Ice and Fire ------------
Line 3,119:
Frost Robert -----------------------'''
for line in text.split('\n'): print(' '.join(line.split()[::-1]))</
'''Output''':
<
Some say the world will end in fire,
Line 3,132:
... last paragraph elided ...
----------------------- Robert Frost</
=={{header|Quackery}}==
<
$ ""
$ " fire, in end will world the say Some "
Line 3,151:
witheach
[ echo$ sp ]
cr ]</
{{out}}
Line 3,168:
=={{header|R}}==
<syntaxhighlight lang="r">
whack <- function(s) {
paste( rev( unlist(strsplit(s, " "))), collapse=' ' ) }
Line 3,187:
for (line in poem) cat( whack(line), "\n" )
</syntaxhighlight>
{{out}}
Line 3,208:
(Everything that happens in R is a function-call.)
<syntaxhighlight lang="r">
> `{` <- function(s) rev(unlist(strsplit(s, " ")))
> {"one two three four five"}
[1] "five" "four" "three" "two" "one"
</syntaxhighlight>
You had better restart your REPL after trying this.
=={{header|Racket}}==
<
(require racket/string)
Line 3,244:
(begin (displayln (split-reverse l))
(loop (read-line poem-port))))))
</syntaxhighlight>
In Wheeler-readable/sweet notation (https://readable.sourceforge.io/) as implemented by Asumu Takikawa (https://github.com/takikawa/sweet-racket):
<
#lang sweet-exp racket/base
require racket/string
Line 3,276:
displayln split-reverse(l)
loop read-line(poem-port)
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
We'll read input from stdin
<syntaxhighlight lang="raku"
{{out}}
<pre>------------ Fire and Ice ----------
Line 3,295:
=={{header|Red}}==
<
foreach line
split
Line 3,310:
print reverse split line " "
]
</syntaxhighlight>
=={{header|REXX}}==
===natural order===
This REXX version process the words in a natural order (first to last).
<
@.=; @.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. */</
'''output''' 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).
<
@.=; @.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. */</
'''output''' is the same as the 1<sup>st</sup> REXX version. <br><br>
=={{header|Ring}}==
<
aList = str2list("
---------- Ice and Fire ------------
Line 3,392:
for y in aList2 see y + " " next see nl
next
</syntaxhighlight>
Output
<
------------ Fire and Ice ----------
Line 3,405:
... last paragraph elided ...
----------------------- Robert Frost
</syntaxhighlight>
=={{header|Ruby}}==
<
---------- Ice and Fire ------------
Line 3,420:
Frost Robert -----------------------
EOS
.each_line.map {|line| line.split.reverse.join(' ')}</
Output the same as everyone else's.
=={{header|Run BASIC}}==
<
read string$
j = 1
Line 3,446:
data "... elided paragraph last ..."
data ""
data "Frost Robert -----------------------"</
Output:
<pre>------------ Fire and Ice ----------
Line 3,460:
=={{header|Rust}}==
<
"---------- Ice and Fire ------------
Line 3,482:
.collect::<Vec<_>>() // Collect lines into Vec<String>
.join("\n")); // Concatenate lines into String
}</
=={{header|S-lang}}==
<
["---------- Ice and Fire ------------",
"fire, in end will world the say Some",
Line 3,500:
array_reverse(ln);
() = printf("%s\n", strjoin(ln, " "));
}</
{{out}}
<pre>------------ Fire and Ice ----------
Line 3,515:
{{works with|Scala|2.9.x}}
<
"""| ---------- Ice and Fire ------------
Line 3,531:
.foreach{println}
}</
{{out}}
Line 3,550:
{{works with|Gauche Scheme}}
<syntaxhighlight lang="scheme">
(for-each
(lambda (s) (print (string-join (reverse (string-split s #/ +/)))))
Line 3,565:
Frost Robert -----------------------"
#/[ \r]*\n[ \r]*/))
</syntaxhighlight>
<b>Output:</b>
<pre>
Line 3,581:
=={{header|sed}}==
<
G
Line 3,587:
s/^[[:space:]]*\([^[:space:]][^[:space:]]*\)\(.*\n\)/\2 \1/
t loop
s/^[[:space:]]*//</
=={{header|Seed7}}==
<
const array string: lines is [] (
Line 3,617:
writeln;
end for;
end func;</
{{out}}
Line 3,634:
=={{header|SenseTalk}}==
<
---------- Ice and Fire ------------
Line 3,650:
put (each word of it) reversed joined by space
end repeat
</syntaxhighlight>
{{out}}
<pre>
Line 3,666:
=={{header|Sidef}}==
<
__DATA__
Line 3,678:
... elided paragraph last ...
Frost Robert -----------------------</
=={{header|Smalltalk}}==
<
poem := '---------- Ice and Fire ------------
Line 3,694:
(poem lines collect: [ :line | ((line splitOn: ' ') reverse) joinUsing: ' ' ]) joinUsing: (String cr).
</syntaxhighlight>
{{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.)
<
fire, in end will world the say Some
Line 3,733:
print();
});</
=={{header|Standard ML}}==
<
" ---------- 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</
=={{header|Swift}}==
<
// convenience extension for better clarity
Line 3,774:
let output = input.lines.map { $0.words.reverse().joinWithSeparator(" ") }.joinWithSeparator("\n")
print(output)</
{{out}}
<pre>
Line 3,790:
=={{header|Tailspin}}==
<
def input: ['---------- Ice and Fire ------------',
'',
Line 3,810:
$input... -> '$ -> words -> $(last..first:-1)...;
' -> !OUT::write
</syntaxhighlight>
=={{header|Tcl}}==
<
"---------- Ice and Fire ------------"
""
Line 3,829:
# This would also work for data this simple:
### puts [lreverse $line]
}</
{{out}}
<pre>
Line 3,845:
Alternatively…
{{works with|Tcl|8.6}}
<
=={{header|TXR}}==
Run from command line:
<syntaxhighlight lang
'''Solution:'''
<
@ (some)
@(coll)@{words /[^ ]+/}@(end)
Line 3,864:
@ (end)
@(end)
</syntaxhighlight>
New line should be present after the last @(end) terminating vertical definition.
i.e.
<
[EOF]</
not
<syntaxhighlight lang
=={{header|UNIX Shell}}==
{{works with|bash}}
<
for ((i=${#words[@]}-1; i>=0; i--)); do
printf "%s " "${words[i]}"
Line 3,890:
Frost Robert -----------------------
END</
{{works with|ksh}}
Same as above, except change <
=={{header|VBA}}==
<syntaxhighlight lang="vb">
Option Explicit
Line 3,933:
ReverseLine = Join(R, Separat)
End If
End Function</
{{Out}}
<pre>------------- Fire And Ice -------------
Line 3,947:
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
Option Explicit
Line 3,987:
objOutFile.Close
Set objFSO = Nothing
</syntaxhighlight>
{{Out}}
Line 4,005:
=={{header|Vlang}}==
<
mut n := [
"---------- Ice and Fire ------------",
Line 4,031:
println(t)
}
}</
'''Simpler version:'''
<
"---------- Ice and Fire ------------",
" ",
Line 4,052:
it.fields().reverse().join(' ').trim_space()
).join('\n')
)</
Line 4,070:
=={{header|Wren}}==
<
"---------- Ice and Fire ------------",
" ",
Line 4,087:
tokens = tokens[-1..0]
System.print(tokens.join(" "))
}</
{{out}}
Line 4,104:
=={{header|XBS}}==
<
(x=="")&=>send x+"<br>";
set sp = x::split(" ");
Line 4,125:
foreach(v of lines){
log(revWords(v));
}</
{{out}}
<pre>
Line 4,141:
=={{header|XPL0}}==
<
def LF=$0A, CR=$0D;
Line 4,181:
Text(0, Str);
CrLf(0);
]</
{{out}}
Line 4,198:
=={{header|Yabasic}}==
<
data " "
data " fire, in end will world the say Some "
Line 4,223:
break
end if
loop</
=={{header|zkl}}==
<
#<<<
"---------- Ice and Fire ------------
Line 4,242:
text.pump(11,Data,fcn(s){ // process stripped lines
s.split(" ").reverse().concat(" ") + "\n" })
.text.print();</
{{out}}
<pre>
|