8.10 Initializing a NULL string variable. 4tH 4tH Forth compiler
โฆษณา
โฆษณา
CHAPTER 8. 4TH ARRAYS
8.10
Initializing a NULL string variable
82
If you’re not sure what that means, it means we’re initializing a string variable to an empty string. Well, that’s very easy:
0 name c!
pad 0 name place
0 dup name place
Choose any of these three. And all these constucts are compatible with ANS-Forth.
8.11
Getting the length of a string variable
You get the length of a string variable by using the word ’COUNT’. It will not only return the length of the string variable, but also the string address. It is illustrated by this short program:
32 string greeting \ define string greeting s" Hello!" greeting place \ set string to ’Hello!’ greeting count
." String length: " . cr drop
\ get string length
\ print the length
\ discard the address
Most string handling words return or take an address/count pair. One of the exceptions is the string variable itself (see section 8.9). To copy the contents of an address/count pair represented string into a string variable, we use ’PLACE’. In order to convert a string variable back to an address/count pair represented string, we use ’COUNT’:
32 string my-string s" This is a string" my-string place my-string count
." Length : " . cr
." Address: " . cr
\ create a string variable
\ create an address/count
\ pair represented string
\ copy it into the variable
\ convert it into an address/count pair
\ show the length
\ show the address
Note that the contents of the string variable do not change by a ’COUNT’ conversion!
8.12
Printing a string variable
Printing a string variable is pretty straight forward. The word that is required to print a string variable is ’TYPE’. It requires an address/count pair. Yes, that are the values that are left on the stack by ’COUNT’! So printing a string means issuing both ’COUNT’ and
’TYPE’:
32 string greeting s" Hello!" greeting place greeting count type cr
\ define string greeting
\ set string to ’Hello!’
\ print the string
If you don’t like this you can always define a word like ’PRINT$’:
: print$ count type ;
32 string greeting s" Hello!" greeting place greeting print$ cr
\ define string greeting
\ set string to ’Hello!’
\ print the string
ดาวน์โหลด
โฆษณา