Reverse words in a string: Difference between revisions

(→‎{{header|Logo}}: Add implementation.)
Line 835:
----------------------- Robert Frost
</pre>
 
=={{header|Forth}}==
The method shown is based on submissions in comp.lang.forth. Comments have been added for those less familiar with reading Forth. This example makes use of the internal Forth parser and calls PARSE-NAME which is a Forth 2012 word that parses the input stream, ignores leading spaces and delimits at the space character.
<lang>create buf 1000 chars allot \ string buffer
buf value pp \ pp points to buffer address
 
: tr ( caddr u -- )
dup >r pp swap cmove \ move string into buffer
r> pp + to pp ; \ advance pointer by u bytes
 
: collect ( -- addr len .. addr[n] len[n]) \ words deposit on data stack
begin
parse-name dup \ parse input stream, dup the len
while \ while stack <> 0
tuck pp >r tr r> swap
repeat
2drop ; \ clean up stack
 
: reverse ( -- )
buf to pp \ initialize pointer to buffer address
collect
depth 2/ 0 ?do type bl emit loop \ print strings with a space
cr ; \ final new line
 
reverse ---------- Ice and Fire ------------
reverse
reverse fire, in end will world the say Some
reverse ice. in say Some
reverse desire of tasted I've what From
reverse fire. favor who those with hold I
reverse
reverse ... elided paragraph last ...
reverse
reverse Frost Robert -----------------------</lang>
 
== Output ==
Interpreted at the Forth console
<pre>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
ok</pre>
 
=={{header|Fortran}}==
Anonymous user