How to split a long string into separate words in Commodore BASIC

Here’s a quick word splitter routine for CBM BASIC. It takes phrase and “explodes” all words into an array, removing spaces. Feel free to adopt it for your own needs.

10 rem word splitter
20 rem splits a long phrase into words at a space
30 input "tell me something";a$
40 rem clear current array of words
50 for i=0 to 10: wd$(i)="": next: wd=1
60 rem detect spaces
70 for i=1 to len(a$)
80 wd$(0)=mid$(a$,i,1)
90 if wd$(0)=" " then wd=wd+1: next
100 wd$(wd)=wd$(wd)+wd$(0): next
110 print
120 rem print all words
130 for i=1 to 10
140 if wd$(i)="" then 160
150 print wd$(i)
160 next

Line 50 clears an array of 10 words called WD$(n). We also setup a word counter called WD. So in this example we can only detect a maximum of ten words. If you need more, you must DIM the array first.

Lines 70 loops through all characters in our phrase. We make use of the first element in our array WD$(0) to store each single character. If it’s a space, we’ll increase the word counter and move on to the next character. If it’s not (line 80), then we’ll add this character to the current word which is stored in WD$(WD).

The rest of the code simply prints each word on a new line to see our handy work.





Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.