Level 1, lesson 18

# 1.18 Fetching individual characters

Take a look at this small program:

         32 string one                   \ define string one
         " Hans" one copy                \ initialize string one
         drop                            \ drop the address

What is the second character of string "one"? Sure, its an "a". But how can you let your program determine that? You can't use '@' because that word can only access variables.

Sure, you can do that in 4tH, but it requires a new word, called 'C@'. Think of a string as an array of characters and you will find it much easier to picture the idea. Arrays in 4tH always start with zero instead of one. So accessing the first character might be done with:

         one 0 th c@

We do not recommend using this construction, although it will work perfectly. If you never want to convert your program to Forth you might even choose to keep it that way. We recommend the construction:

         one 0 chars + c@

Which is slightly more wordy. 4tH will compile both constructions in exactly the same way. Anyway, accessing the second character is easy now:

         one 1 chars + c@

This is the complete program:

         32 string one                   \ define string one
         " Hans" one copy                \ initialize string one
         drop                            \ drop the address
         one 1 chars + c@                \ get the second character
         emit cr                         \ print it

Of course we can optimize it a little by using the address 'COPY' left on the stack:

         32 string one                   \ define string one
         " Hans" one copy                \ initialize string one
         1 chars + c@                    \ get the second character
         emit cr                         \ print it