String constants. 4tH 4tH Forth compiler
Pubblicità
Pubblicità
CHAPTER 8. 4TH ARRAYS 81
And what about string literals with quotes. Easy, there is an equivalent to ’S”’ that does the same thing: s| "This is a string with quotes"|
." Length : " . cr
." Address: " . cr
\ show the length
\ show the address
Instead of a quote, the string is delimited by a bar. And what about string literals that include them both? Bad luck? Well, almost but not quite. Just take a look at section 13.17.
8.8
String constants
String constants work the same way as numeric constants:
10 constant ten ten . cr
\ define a string constant
\ equivalent to: 10 . cr
In fact, you give a name to a literal value. After that, you can refer to that literal throughout your program by using its name. String constants do the same thing. Take a look at this little piece of code: s" This is a string"
." Length : " . cr
." Address: " . cr
\ create a temporary string
\ show the length
\ show the address
Now we do the same thing, but this time we define a string constant by using ’SCON-
STANT’: s" This is a string" sconstant mystring
\ define a string constant mystring
." Length : " . cr
\ now we use the string constant
\ show the length
." Address: " . cr \ show the address
Why use string constants? Well, first of all, if you use a string constant throughout your program, it will save you some editing when you have to change your program for one reason or another. Second, it will make your program a little smaller.
8.9
Initializing string variables
You can initialize a string with the ’S"’ word. If you want the string to contain your first name use this construction: s" Hello!" name place
The word ’PLACE’ copies the contents of a string literal into a string-variable.
If you still don’t understand it yet, don’t worry. As long as you use this construction, you’ll get what you want. Just remember that assigning a string literal to a string that is too short will result in an error or even worse, corrupt other strings.
Scarica
Pubblicità