Reverse words in a string: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎Tcl: Added implementation)
Line 234: Line 234:
end /*j*/ /*stick a fork in it, we're done.*/</lang>
end /*j*/ /*stick a fork in it, we're done.*/</lang>
'''output''' when using the ten lines of input:
'''output''' when using the ten lines of input:
<pre>
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost
</pre>

=={{header|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>
{{out}}
<pre>
<pre>
------------ Fire and Ice ----------
------------ Fire and Ice ----------

Revision as of 12:51, 13 April 2014

Reverse words in a string is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

The task is to reverse the order of all tokens in a number of strings.

  • Hey you, Bub!   would be shown reversed as:   Bub! you, Hey
  • Tokens   are any non-blank characters separated by blanks.
  • You can consider the ten strings as ten lines, and tokens as words.
  • Multiple (or superfluous blanks) can be compressed into one blank.
  • Some strings have no words, so a blank string (line) should be shown.
  • Display the strings in order (1st, 2nd, 3rd, ···), and one string per line.
  • Keep the letter case (upper/lower) and all punctuation intact.
  • This example hasn't any tabs or other non-visible characters.
             (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 -----------------------  ║
     ╚════════════════════════════════════════╝

AWK

<lang AWK>

  1. 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>

  1. 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.

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.

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>

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>

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

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