17.6.1.0935 COMPARE STRING
Compare the string specified by c-addr1 u1 to the string specified by c-addr2 u2. The strings are compared, beginning at the given addresses, character by character, up to the length of the shorter string or until a difference is found. If the two strings are identical, n is zero. If the two strings are identical up to the length of the shorter string, n is minus-one (-1) if u1 is less than u2 and one (1) otherwise. If the two strings are not identical up to the length of the shorter string, n is minus-one (-1) if the first non-matching character in the string specified by c-addr1 u1 has a lesser numeric value than the corresponding character in the string specified by c-addr2 u2 and one (1) otherwise.
Testing:
T{ s1 PAD SWAP CMOVE -> }T \ Copy s1 to PAD
T{ s1 PAD OVER COMPARE -> 0 }T
T{ s1 PAD 6 COMPARE -> 1 }T
T{ PAD 10 s1 COMPARE -> -1 }T
T{ s1 PAD 0 COMPARE -> 1 }T
T{ PAD 0 s1 COMPARE -> -1 }T
T{ s1 s6 COMPARE -> 1 }T
T{ s6 s1 COMPARE -> -1 }T
: "abdde" S" abdde" ;
: "abbde" S" abbde" ;
: "abcdf" S" abcdf" ;
: "abcdee" S" abcdee" ;
T{ s1 "abdde" COMPARE -> -1 }T
T{ s1 "abbde" COMPARE -> 1 }T
T{ s1 "abcdf" COMPARE -> -1 }T
T{ s1 "abcdee" COMPARE -> 1 }T
: s11 S" 0abc" ;
: s12 S" 0aBc" ;
T{ s11 s12 COMPARE -> 1 }T
T{ s12 s11 COMPARE -> -1 }T
ContributeContributions
agsb
[193] How many cells can be compared ? Must have any limit ?Request for clarification2021-04-25 19:52:16
JimPeterson
[398] Possible Reference ImplementationSuggested reference implementation2025-08-09 15:54:10
I suggest the following as a reference implementation:
: _cmp ( x1 x2 -- -1|0|1 ) - DUP IF 0< 1 OR THEN ;
: COMPARE ( addr1 u1 addr2 u2 -- -1|0|1 )
ROT 2DUP SWAP _cmp >R
MIN ?DUP IF
0 DO
COUNT >R SWAP COUNT R> _cmp ?DUP IF
NIP NIP UNLOOP R> DROP EXIT
THEN
SWAP
LOOP
THEN
2DROP
R>
;