Reverse words in a string
You are encouraged to solve this task according to the task description, using any language you may know.
The task is to reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
- Example: “Hey you, Bub!” would be shown reversed as: “Bub! you, Hey”
Tokens are any non-space characters separated by spaces (formally, white-space); the visible punctuation forms part of the word within which it is located and should not be modified. You may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space. Some strings have no tokens, so an empty string (or one just containing spaces) would be the result. Display the strings in order (1st, 2nd, 3rd, ···), and one string per line. (You can consider the ten strings as ten lines, and the tokens as words.)
- Input data
(ten lines within the box) line ╔════════════════════════════════════════╗ 1 ║ ---------- Ice and Fire ------------ ║ 2 ║ ║ ◄─── a blank line here. 3 ║ fire, in end will world the say Some ║ 4 ║ ice. in say Some ║ 5 ║ desire of tasted I've what From ║ 6 ║ fire. favor who those with hold I ║ 7 ║ ║ ◄─── a blank line here. 8 ║ ... elided paragraph last ... ║ 9 ║ ║ ◄─── a blank line here. 10 ║ Frost Robert ----------------------- ║ ╚════════════════════════════════════════╝
Applesoft BASIC
<lang ApplesoftBasic>100 DATA"---------- ICE AND FIRE ------------" 110 DATA" " 120 DATA"FIRE, IN END WILL WORLD THE SAY SOME" 130 DATA"ICE. IN SAY SOME " 140 DATA"DESIRE OF TASTED I'VE WHAT FROM " 150 DATA"FIRE. FAVOR WHO THOSE WITH HOLD I " 160 DATA" " 170 DATA"... ELIDED PARAGRAPH LAST ... " 180 DATA" " 190 DATA"FROST ROBERT -----------------------"
200 FOR L = 1 TO 10 210 READ T$ 220 I = LEN(T$) 240 IF I THEN GOSUB 300 : PRINT W$; : IF I THEN PRINT " "; : GOTO 240 250 PRINT 260 NEXT L 270 END
300 W$ = "" 310 FOR I = I TO 1 STEP -1 320 IF MID$(T$, I, 1) = " " THEN NEXT I : RETURN 330 FOR I = I TO 1 STEP -1 340 C$ = MID$(T$, I, 1) 350 IF C$ <> " " THEN W$ = C$ + W$ : NEXT I 360 RETURN </lang>
AWK
<lang AWK>
- syntax: GAWK -f REVERSE_WORDS_IN_A_STRING.AWK
BEGIN {
text[++i] = "---------- Ice and Fire ------------" text[++i] = "" text[++i] = "fire, in end will world the say Some" text[++i] = "ice. in say Some" text[++i] = "desire of tasted I've what From" text[++i] = "fire. favor who those with hold I" text[++i] = "" text[++i] = "... elided paragraph last ..." text[++i] = "" text[++i] = "Frost Robert -----------------------" leng = i for (i=1; i<=leng; i++) { n = split(text[i],arr," ") for (j=n; j>0; j--) { printf("%s ",arr[j]) } printf("\n") } exit(0)
} </lang>
output:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
C
<lang c>#include <stdio.h>
- include <ctype.h>
void rev_print(char *s, int n) {
for (; *s && isspace(*s); s++); if (*s) { char *e; for (e = s; *e && !isspace(*e); e++); rev_print(e, 0); printf("%.*s%s", (int)(e - s), s, " " + n); } if (n) putchar('\n');
}
int main(void) {
char *s[] = { "---------- Ice and Fire ------------", " ", "fire, in end will world the say Some", "ice. in say Some ", "desire of tasted I've what From ", "fire. favor who those with hold I ", " ", "... elided paragraph last ... ", " ", "Frost Robert -----------------------", 0 }; int i; for (i = 0; s[i]; i++) rev_print(s[i], 1);
return 0;
}</lang> Output is the same as everyone else's.
Common Lisp
<lang lisp>(defun split-and-reverse (str)
(labels ((iter (s lst) (let ((s2 (string-trim '(#\space) s))) (if s2 (let ((word-end (position #\space s2))) (if (and word-end (< (1+ word-end) (length s2))) (iter (subseq s2 (1+ word-end)) (cons (subseq s2 0 word-end) lst)) (cons s2 lst))) lst)))) (iter str NIL)))
(defparameter *poem*
"---------- Ice and Fire ------------ fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I ... elided paragraph last ... Frost Robert -----------------------")
(with-input-from-string (s *poem*)
(loop for line = (read-line s NIL) while line do (format t "~{~a~#[~:; ~]~}~%" (split-and-reverse line))))</lang>
Output is the same as everyone else's.
D
<lang d>void main() {
import std.stdio, std.string, std.range;
immutable text =
"---------- Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------";
writefln("%(%-(%s %)\n%)", text.splitLines.map!(r => r.split.retro));
}</lang> The output is the same as the Python entry.
Go
<lang go>package main
import (
"fmt" "strings"
)
// a number of strings var n = []string{
"---------- Ice and Fire ------------", " ", "fire, in end will world the say Some", "ice. in say Some ", "desire of tasted I've what From ", "fire. favor who those with hold I ", " ", "... elided paragraph last ... ", " ", "Frost Robert -----------------------",
}
func main() {
for i, s := range n { t := strings.Fields(s) // tokenize // reverse last := len(t) - 1 for j := 0; j < last/2; j++ { t[j], t[last-j] = t[last-j], t[j] } n[i] = strings.Join(t, " ") } // display result for _, t := range n { fmt.Println(t) }
}</lang>
J
Treated interactively:
<lang J> ([:;@|.[:<;.1 ' ',]);._2]0 :0
Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------
)
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
</lang>
Julia
<lang Julia>revstring (str) = join(reverse(split(str, " ")), " ")</lang>
- Output:
julia> revstring("Hey you, Bub!") "Bub! you, Hey" julia> s = IOBuffer( "---------- Ice and Fire ------------ fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I ... elided paragraph last ... Frost Robert -----------------------") julia> for line in eachline(s) println(revstring(chomp(line))) end ------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
Mathematica
<lang Mathematica>poem = "---------- Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I ... elided paragraph last ... Frost Robert -----------------------";
lines = StringSplit[poem, "\n"]; wordArray = StringSplit[#] & @ lines ; reversedWordArray = Reverse[#] & /@ wordArray ; linesWithReversedWords =
StringJoin[Riffle[#, " "]] & /@ reversedWordArray;
finaloutput = StringJoin[Riffle[#, "\n"]] & @ linesWithReversedWords</lang>
- Output:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
Objeck
<lang objeck>use Collection;
class Reverselines {
function : Main(args : String[]) ~ Nil { lines := List->New(); lines->AddBack("---------- Ice and Fire ------------"); lines->AddBack(""); lines->AddBack("fire, in end will world the say Some"); lines->AddBack("ice. in say Some"); lines->AddBack("desire of tasted I've what From"); lines->AddBack("fire. favor who those with hold I"); lines->AddBack(""); lines->AddBack("... elided paragraph last ..."); lines->AddBack(""); lines->AddBack("Frost Robert -----------------------"); lines->Rewind(); each(i : lines) { words := lines->Get()->As(String)->Split(" "); if(words <> Nil) { for(j := words->Size() - 1; j > -1; j-=1;) { IO.Console->Print(words[j])->Print(" "); }; }; IO.Console->PrintLine(); lines->Next(); }; }
}</lang>
Output:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
Perl 6
<lang>say .words.reverse for q:to/END/.lines;
Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I
... elided paragraph last ...
Frost Robert ----------------------- END </lang>
- Output:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
Python
<lang python>>>> text = \
Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I
... elided paragraph last ...
Frost Robert ----------------------- >>> for line in text.split('\n'): print(' '.join(line.split()[::-1]))
Fire and Ice ----------
Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire.
... last paragraph elided ...
Robert Frost
>>> </lang>
Racket
<lang racket>#lang racket/base
(require racket/string)
(define (split-reverse str)
(string-join (reverse (string-split str))))
(define poem
"---------- Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------")
(let ([poem-port (open-input-string poem)])
(let loop ([l (read-line poem-port)]) (unless (eof-object? l) (begin (displayln (split-reverse l)) (loop (read-line poem-port))))))
</lang>
REXX
<lang rexx>/*REXX pgm reverses the order of tokens in a string, but not the letters*/ @. = @.1 = "---------- Ice and Fire ------------" @.2 = ' ' @.3 = "fire, in end will world the say Some" @.4 = "ice. in say Some" @.5 = "desire of tasted I've what From" @.6 = "fire. favor who those with hold I" @.7 = ' ' @.8 = "... elided paragraph last ..." @.9 = ' ' @.10 = "Frost Robert -----------------------"
do j=1 while @.j\==; $= /*process each "line"; nullify $.*/ do k=1 for words(@.j) /*process each word in the string*/ $=word(@.j,k) $ /*prepend the word to a new line.*/ end /*k*/ /* [↑] could do this another way*/ say $ /*display newly constructed line.*/ end /*j*/ /*stick a fork in it, we're done.*/</lang>
output when using the ten lines of input:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
Ruby
<lang ruby>def reverse_words(strings)
strings.each_line.map {|line| line.split.reverse.join(" ")}
end
str = <<'EOS'
Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I
... elided paragraph last ...
Frost Robert ----------------------- EOS
puts reverse_words(str)</lang>
Output is the same as everyone else's.
Tcl
<lang tcl>set lines {
"---------- Ice and Fire ------------" "" "fire, in end will world the say Some" "ice. in say Some" "desire of tasted I've what From" "fire. favor who those with hold I" "" "... elided paragraph last ..." "" "Frost Robert -----------------------"
} foreach line $lines {
puts [join [lreverse [regexp -all -inline {\S+} $line]]] # This would also work for data this simple: ### puts [lreverse $line]
}</lang>
- Output:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
Alternatively…
<lang tcl>puts [join [lmap line $lines {lreverse $line}] "\n"]</lang>
zkl
<lang zkl>text:=Data(0,String, "---------- Ice and Fire ------------", "", "fire, in end will world the say Some", "ice. in say Some", "desire of tasted I've what From", "fire. favor who those with hold I", "", "... elided paragraph last ...", "", "Frost Robert -----------------------");
text.pump(Data,fcn(s){
s.split(" ").filter().reverse().concat(" ")+"\n" }) .text.println();</lang>
- Output:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost