8.13 Copying a string variable. 4tH 4tH Forth compiler
जाहिरात
जाहिरात
CHAPTER 8. 4TH ARRAYS
8.13
Copying a string variable
You might want to copy one string variable to another. Let’s take a look at this example:
32 string one
32 string two s" Greetings!" one place one count two place two count type cr
\ define the first string
\ define the second string
\ initialize string one
\ get the length of string one
\ and copy it into string two
\ print string two
83
First we place the string ”Greetings!” into a string variable. ’S”’ will put an address/count pair on the stack, that is consumed by ’PLACE’. Variable ”ONE” only puts its address on the stack, that is converted into an address/count pair by ’COUNT’. After it has been consumed again by ’PLACE’ we need ’COUNT’ again to provide ’TYPE’ with an address/count pair.
8.14
The string terminator
In order for ’COUNT’ to work, it has to know where the string stops. So a special character at the end of the string, the string terminator, is used to indicate the end of an ASCIIZ string.
It has nothing to do with Arnold Schwarzenegger obliterating innocent strings! It is simply a character, having the ASCII value zero. It may also be referred to as the NULL-character.
Although most strings in 4tH will be terminated automatically it is considered bad style to rely on that.
If you have doubts, you can always convert an address/count pair to a terminated string by applying ’>STRING’, although you have to take care that nothing is overwritten and enough space is available. As a rule of the tumb you might say that ’>STRING’ can safely be applied to all string variables.
8.15
Slicing strings
Slicing strings is just like copying strings. We just don’t copy all of it and we don’t always start copying at the beginning of a string. We’ll show you what we mean:
32 string one s" Hans Bezemer" one place one count 2dup type cr
1 /string
2dup type cr
1 /string
2dup type cr
1 /string type cr
\ define string one
\ initialize string one
\ duplicate and print it
\ move one character forward
\ duplicate and print it again
\ move one character forward
\ duplicate and print it again
\ move one character forward
\ print it for the last time
First it will print "Hans Bezemer", then "ans Bezemer", then "ns Bezemer" and finally
"s Bezemer". The word ’/STRING’ adjusts the address/count pair by a given number of characters, in this case one character. The word ’2DUP’ is much like ’DUP’, but it copies the top two values on the stack. It is functionally equivalent to: over over
डाउनलोड
जाहिरात