1.6 Getting the length of a string

You get the length of a string by using the word 'COUNT'. It will not only return the length of the string, but also the string address. It is illustrated by this short program:

     32 string greeting              \ define string greeting
     " Hello!" greeting copy         \ set string to 'Hello!'
     drop                            \ drop the value COPY left
     greeting count                  \ get string length
     ." String length: " . cr        \ print the length
     drop                            \ discard the address

You usually have nothing to do with the string address. However, it may be required by other words like we will see in the following section. If you just want the bare length of the string you can always define a word like 'length$':

     : length$ count swap drop ;
     32 string greeting              \ define string greeting
     " Hello!" greeting copy         \ set string to 'Hello!'
     drop                            \ drop the value COPY left
     greeting length$                \ get string length
     ." String length: " . cr        \ print the length

We wrote in previous sections that 'COPY' left a value on the stack that was equivalent with writing the name of the string variable. We can now see why 'COPY' does that. Instead of writing:

     " Hello!" greeting copy         \ set string to 'Hello!'
     drop                            \ drop the value COPY left
     greeting length$                \ get string length

We could write:

     " Hello!" greeting copy         \ set string to 'Hello!'
     length$                         \ get string length

This kind of optimization makes a 4tH program faster and more compact, which is a rare thing these days!