LoginLogin

HOWTO: Split a string in SmileBasic into sub-strings. Think of it like a mini library.

Root / Programming Questions / [.]

CoinzReturnsCreated:
DIM LIST$[25]
CLS
@MAIN

INPUT$="HI HOW ARE YOU"
PRINT "THE INPUT WAS " +INPUT$
PRINT "sPLITTING INPUT"
GOSUB @SPLIT

PRINT "------RESULTS------"
FOR T=0 TO FOUND
PRINT LIST$[T]


NEXT T

VSYNC 1
INPUT "ENTER TO QUIT";EN$

END

@SPLIT
L=LEN(INPUT$)
INDEX=0
LASTFROM=0
CURRENTFROM=0
FOUND=-1 'TO CONFIRM LATER

FOR T=0 TO L-1

GETCHAR INPUT$, T OUT C$
IF C$=" " THEN
FOUND=FOUND+1
CURRENTFROM=T
'----ACCOUNT FOR THE SPACE CHARACTER
----BUT ONLY IF THIS ISNT THE FIRST PASS
IF FOUND>0 THEN
LIST$[FOUND]=MID$(INPUT$, LASTFROM+1, T-LASTFROM)
ENDIF
'--ON THE FIRST SPACE FOUND THERE WONT
'--BE A SPACE CHARACTER TO CUT OFF ON THE LEFT
IF FOUND==0 THEN
LIST$[FOUND]=MID$(INPUT$, LASTFROM, T-LASTFROM)
ENDIF

LASTFROM=CURRENTFROM 'THIS IS IMPORTANT BECAUSE NOW THE LAST FOUND SPACE IS THIS CURRENT ONE
ENDIF

NEXT T

'GET THE VERY LAST WORD IN THE STRING
FOUND=FOUND+1
CURRENTFROM=L
LAST$=MID$(INPUT$, LASTFROM+1, CURRENTFROM-LASTFROM)
LIST$[FOUND]=LAST$

RETURN

DEF GETCHAR INPUT$, INDEX OUT C$

C$=MID$(INPUT$, INDEX, 1)
END

You should make it a function instead of using GOSUB EDIT:
ACLS

INPUT$="HI HOW ARE YOU"
PRINT "THE INPUT WAS "+INPUT$
PRINT "SPLITTING INPUT"
DIM LIST$[0]
LIST$=SPLIT$(INPUT$)

PRINT "------RESULTS------"
FOR T=0 TO LEN(LIST$)-1
PRINT LIST$[T]
NEXT T

DEF SPLIT$(INPUT$)
 VAR L=LEN(INPUT$)
 VAR INDEX=0
 VAR LASTFROM=0
 VAR CURRENTFROM=0
 VAR FOUND=-1 'TO CONFIRM LATER
 VAR T
 VAR C$
 FOR T=0 TO L-1
  
  GETCHAR INPUT$, T OUT C$
  IF C$==" " THEN
   FOUND=FOUND+1
   CURRENTFROM=T
   '----ACCOUNT FOR THE SPACE CHARACTER
   '----BUT ONLY IF THIS ISNT THE FIRST PASS
   IF FOUND>0 THEN
    PUSH LIST$,MID$(INPUT$, LASTFROM+1, T-LASTFROM)
   ENDIF
   '--ON THE FIRST SPACE FOUND THERE WONT
   '--BE A SPACE CHARACTER TO CUT OFF ON THE LEFT
   IF FOUND==0 THEN
    PUSH LIST$[FOUND],MID$(INPUT$, LASTFROM, T-LASTFROM)
   ENDIF
   
   LASTFROM=CURRENTFROM 'THIS IS IMPORTANT BECAUSE NOW THE LAST FOUND SPACE IS THIS CURRENT ONE
  ENDIF
  
 NEXT T
 
 'GET THE VERY LAST WORD IN THE STRING
 FOUND=FOUND+1
  CURRENTFROM=L
  LAST$=MID$(INPUT$, LASTFROM+1, CURRENTFROM-LASTFROM)
  PUSH LIST$,LAST$
  
END

DEF GETCHAR INPUT$, INDEX OUT C$

 C$=MID$(INPUT$, INDEX, 1)
END