I was thinking about strings, how they work etc. I looked at this site
http://www.forth.com/starting-forth/sf11/sf11.html and read the tutorial
for beginners. My definition of strings below, not perfect, but it DOES>
things, it's fun

Code: Select all
( Definitions CHAR, [CHAR] )
( Takes a char from the input stream )
( leaves ASCII value on the stack )
: CHAR BL WORD 1+ C@ ; : [CHAR] CHAR ; IMMEDIATE
( Create string )
: S" ( S" ..." --- adr n )
[CHAR] " LITERAL WORD DUP COUNT PAD SWAP CMOVE
C@ PAD SWAP ;
( Create string variable )
: STRING ( n "name" --- adr n )
CREATE DUP , HERE SWAP DUP ALLOT BLANK
DOES> DUP 2+ SWAP @ ;
( Move string , ad1 +1..+n1 -> ad2 +1.. )
: $MOVE ( ad1 n1 ad2 n2 --- )
2DUP BLANK ROT MIN CMOVE ;
( Print string )
: $. ( ad n --- )
-TRAILING CR TYPE ;
( Compare two strings )
( n=0 equal, n>0 str1>str2, n<0 str1<str2 )
VARIABLE ?SL ( ? same lengths )
: $COMPARE ( ad1 n1 ad2 n2 --- n )
ROT 2DUP - NEGATE ?SL ! MIN
0 DO 2DUP I + C@ SWAP I + C@ - DUP
0 <> IF 0 LEAVE ELSE DROP THEN LOOP
0= IF ROT ROT 2DROP NEGATE ELSE DROP ?SL @ THEN ;
( Fetch a CHAR at string positon m )
: $C@ ( m ad n --- ch )
ROT 1 MAX MIN SWAP + 1- C@ ;
( Stores a CHAR to string positon m )
: $C! ( ch m ad n --- )
ROT 1 MAX MIN SWAP + 1- C! ;
( Some short hand definitions )
: $BL BLANK ; : $! $MOVE ; : $= $COMPARE ; : C. EMIT ;
( Test, create strings [15] and [20] chars long )
15 STRING GREET 20 STRING INGS
( Test, strings are empty on creation )
GREET $. INGS $.
( Test, move string [11] -> GREET [15] )
( Print GREET )
S" HELLO THERE" GREET $MOVE
GREET $.
( Test, move string [24] -> INGS [20] )
( Print INGS )
S" PLEASED TO MEET YOU! ..." INGS $!
INGS $.
( Test, move GREET [15] -> INGS [20] )
( Print INGS )
GREET INGS $!
INGS $.
( Test, put 'x' to GREET at postion 10 )
( Print GREET )
CHAR x 10 GREET $C!
GREET $.
( Test, get chars at position 1,10 from INGS )
1 INGS $C@ CR C.
10 INGS $C@ C.
( Test, compare GREET, INGS )
GREET INGS $= CR .
( Test, compare < > = )
3 STRING TEST CR
S" ABC" TEST $!
S" ABC" TEST $= .
S" ABCD" TEST $= .
S" AB" TEST $= .
S" ABD" TEST $= .
S" ABB" TEST $= .
( Test, blank INGS )
( Print INGS )
INGS $BL
INGS $.
( Test, blank GREET )
( Print GREET )
S" " GREET $!
GREET $.
END_FILE
