Commodore 2001-8 User Manual page 45

Table of Contents

Advertisement

characters and blanks are all counted as part of length.
Strtngs are stored in BASIC with a 3·byte vector. Two bytes are a pointer to the location In memory where
the string is stored and the third byte Is the length, the LEN function extracts this byte.
We can now write a general purpose program to extract the last name from a full name.
10 INPUT"NAME:FIRST, MI, LAsrJA$
20 I = LEN(A$)
30 IF mld$(A$,I,l)=" "THEN 60
401=1-1
50 IF 1>0 GOTO 30
60 PRINT "LAST NAME = ";
MID$(A$, 1+1)
Two variants of MID$ are used here. Line 30 uses the case where a length is specified as the first
parameter. We are using a length of 1 to search for the blank delimiting the last name. Line 60 does not
specify a length in the MID$. Everything beyond the position of the blank is taken.
STRING STORAGE
Strings are stored in the space between the end of your BASIC program and the highest RAM locations.
As
each new string is added, a chain grows downward from the-top of memory.
Storage Is optimized by never creating a copy of a string assigned to a literal. In this case the vector for
the string points to where the literal occurs in text In memory. likewise, if an expression AS =
BS
is
executed, both AS and BS
will
share the same copy of the string. New strtng is required only If a
concatenation or INPUT is executed.
A LARGER EXAMPLE OF STRING FUNCTIONS
Using the string functions described thus far we can write a routine which will shuffle a deck of cards for
us and deal them out one at a time. The following routine has applications In many games like poker or
bridge. Note use of the PET graphics card symbols:
109 REM SET UP DECK WITH ALL S2 CARDS
110 Ci="A.2.3....S*.7.a.9.T.J.Q..,;."
120
Ci=C$+"A.2.3~.S%.7.a.9.T.J.QIfI(."
130 C$=C$+"A+2+3+4+S+6+7+a+9+T+J+Q+K+"
140 O=C $+" A+2+3+4+S+6+7+a+9+1+J +Q+K +"
190 REM PULL A CARD
200 R=2*INT(LEN(Ci)*RND(I)/2+1)-1
201 Ni=MID$(Ci,R,I),Y$=MIDi(Ci,R+l,l)
430 REM SHRINK THE DECK
432 IFR}ITHENT$=LEFTi(Ci,R-l) ,GOT043S
433 T$=""
43S C$=T$+MID$(C$,R+2)
439 REM PRINT A CARD
440 PR INTNi; H,
4S0 IFLEN(Ci)}=ITHEN200
4SS REM END OF DECK
460 INPUT"ANOTHER DEAL
_";2$
470 GOT»10S
READY.
The string C$ is initialized to contain a deck of cards. Two characters represent each card; the suit and
rank. As a card is dealt, N$ contains the rank and Y$ contains the suit. The deck string, CS, shrinks each
time so that unique cards are always dealt.
Statement 105 clears the screen. This is done just for show so that the program can illustrate the dealing
of cards. C$ls initialized in
stateme~ts
110 through 140. C$ls concatenated because the literal
assignment is too large to fit on one line.
41

Advertisement

Table of Contents
loading

This manual is also suitable for:

Pet 2001-8

Table of Contents