In FORTH Reverse a string supplied as (addr length).
- User
In FORTH Reverse a string supplied as (addr length).
- Assistant
In FORTH Reverse a string supplied as (addr length).
In Forth, strings are commonly represented by a starting memory address and a length, as opposed to null-terminated strings in languages like C. To reverse a string in Forth you would define a word (which is like a function in other languages) that takes an address and a length from the stack and reverses the string in place.
Here's how you might define such a word to reverse a string in place:
: reverse ( addr len -- addr )
>r \ save length on the return stack
over + swap \ calculate the address of the last char
1- r> 2/ \ calculate midpoint and restore length to the stack
?DO \ loop from 0 to half the length - 1
over + \ calculate address of the current char from the start
tuck \ duplicate the address for later and bring original to top
c@ \ get the character at the current position
over i - c@ \ get the character from the corresponding end position
>r \ save the end character on the return stack
r> swap \ get the original character and swap the addresses
c! \ write the original character to the end
r> \ retrieve the end character we saved
c! \ write it to the start position
1+ \ move to the next char
LOOP
drop ; \ clean up the stack
Here's how the word works:
DO loop to iterate through the first half of the string.To test this code, you can first allocate a string space, initialize it with a string, and then call the reverse word:
: test-reverse
s" Hello, World!" count
dup allocate throw \ allocate space and get addr
swap over over \ copy (addr addr len)
move \ move string to allocated space
reverse \ we now have address at the top, use for output
type cr \ print reversed string and a newline
swap free throw ; \ free allocated memory
test-reverse
The word test-reverse would output "!dlroW ,olleH" after reversing the given "Hello, World!" string. Remember that since this works directly in memory, you'll need to make sure the space is allocated and that you free it afterward to avoid memory leaks.
Not yet included in a published release.