How do I compare two strings in Forth?

时间秒杀一切 提交于 2019-12-10 21:01:05

问题


And can I do it in an if statement or should I make a helper boolean variable? Here's the code I have so far. By the way, IOX@ is to get input from the user.

: var
compile: VARIABLE
complile: ;

: lock
compile: var realPass$
compile: realPass$ "password" !
compile: ." Enter Password: "
compile: var pass$
compile: IOX@ pass$ !
compile: var match
compile: realPass$=pass$ match ! Unknown token: realPass$=pass$

回答1:


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


来源:https://stackoverflow.com/questions/17381241/how-do-i-compare-two-strings-in-forth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!