The ANS FORTH word to compare strings is COMPARE (c-addr_1 u_1 c-addr_2 u_2 -- n)
. In FORTH a string is created with the s"
word, and a string consists of a memory address and a length. This means that when you're comparing strings, you're providing to COMPARE
the memory address and length of both strings.
The result of COMPARE
is as follows: 0
if the two strings are equal, -1
for less-than, 1
for greater than. This is same as other languages that provide a comparator, or comparison operator. Note, in FORTH true
is -1
, so there is no value to checking the binary return of compare
.
Generally Forth eschews explicit variables in favor of using the stack so using it with IF
directly without an extra variable is fine.
: PWCHECK
COMPARE
IF ." Entry denied."
ELSE ." Welcome friend." THEN
CR
;
S" Hello" ok
S" Goodbye" ok
PWCHECK You are not wanted here. ok
S" Howdy" ok
S" Howdy" ok
PWCHECK Welcome friend. ok