1.11 Comparing strings

If you ever sorted strings you know how indispensable comparing strings is. As we mentioned before, there are very few words in Forth that act on strings. Here is a word that can compare two strings.

If you want to compare two strings casesensitive, you have to set the constant '?IGNORE' to FALSE. In the following example the comparison is case-insensitive. Don't try to understand it. It is still beyond you if you have no previous experience with Forth:

     true constant ?ignore           \ ignore case?
                                     \ compare two strings
     : compare$                    ( a1 a2 -- f )
          count 1+                 ( a1 a2 n )
          dup 0                    ( a1 a2 n n 0 )
          do                       ( a1 a2 f )
               drop                ( a1 a2 )
               over i + c@         ( a1 a2 c1)
               over i + c@         ( a1 a2 c1 c2)
               xor ?ignore         ( a1 a2 n f)
               if                  ( a1 a2 n)
                    32 invert and  ( a1 a2 f)
               then                ( a1 a2 f)
               dup                 ( a1 a2 f f)
               if                  ( a1 a2 f)
               then                ( a1 a2 f)
          >r drop drop r>               ( f )
                                   \ compare two chars
     32 string one                 \ define string one
     " Hans Bezemer" one copy      \ initialize string one
     32 string two                 \ define string two
     " HANS BEZEMER" two copy      \ initialize string two

     compare$                      \ compare two strings
          ." Strings differ"       \ message: strings ok
          ." Strings are the same" \ message: strings not ok
     cr                            \ send CR

Simply pass two strings to 'COMPARE$' and it will return a TRUE flag when the strings are different. This might seem a bit odd, but strcmp() does exactly the same. If you don't like that you can always add '0=' to the end of 'COMPARE$' to reverse the flag.