In this episode I’m demonstrating how to build a word splitter on the Commodore 64. We’ll use string functions to parse a sentence and split each word off into an array of words so that they can be analysed later (for example, as part of an adventure game).
Here’s the code I’m building:
20 input a$ 30 gosub 100 40 print:print wd;" words:" 50 for i=1 to wd 60 print wd$(i) 70 next 99 end 100 rem word splitter 110 lt$="":wd=1 120 for i=1 to len(a$) 130 lt$=mid$(a$,i,1) 140 if lt$=" " then wd=wd+1:next 150 wd$(wd)=wd$(wd)+lt$ 160 next 199 return
The interesting part starts in line 100 and onwards, where I’m building a subroutine that deals with the string functions. In line 110 I’m resetting/initialising two of the three important variables: LT$ holds a single letter from the phrase we’re getting in A$, while WD is counting each word we’re splitting out.
The FOR loop in line 120 parses each letter of the phrase, and if it finds a space character (line 140), the word count is increased. If the letter is not a space, then it’s added to the current word held in WD$(WD). The current word is assembled character by character.
Apologies for the audio quality, I did this on my laptop while sitting on the balcony, hence sea planes flying overhead can be heard (as well as the neighbours dog and kids).
Happy hacking 🙂
Podcast: Download (Duration: 10:26 — 9.6MB)