The Split function breaks a string into an array and returns the highest dimension of the array. The elements of the array are the delimited sub-strings of the input string.
The sub-strings are always returned in the array SP$, 1 is the first sub-string.
Split() trashes the passed in string - if this is a problem consider
this method.
Commonly, after a Split(), one uses the UBound() function to determine the number of substrings. MMbasic does not have UBound but the Split function reports the number of elements. If no delimiter is found, it reports 1 element - with SP(1) as the entire string.
Substrings are not trimmed.
The delimiter can be any length>0.
Compatible with all versions of MMBasic.
Syntax:
NumOfElements=Split(StringToSplit, delimeter)
Example usage:
z=Split(Time$,":")
FOR n=1 TO z
PRINT n,SP$(n)
NEXT
Code:
FUNCTION Split(a$,b$) As Integer' returns the number of dimensions in SP$ always starts from 1 regardless of OPTION BASE
LOCAL INTEGER z,n,m
IF b$="" then Split=0:EXIT FUNCTION ' can't split with an empty delimiter
' if SP$ doesn't exist, the ERASE will cause an error, choose which ON ERROR SKIP you need
'MM.Ver <5.04
ON ERROR SKIP
'MM.Ver >=5.04
ON ERROR SKIP 1
ERASE SP$
z=1:n=0
DO 'count instances of delimiter for DIM SP$()
z=INSTR(z,a$,b$)
IF z=0 THEN
IF n=0 THEN ' no delimeters
DIM SP$(1):SP$(1)=a$:Split=1:EXIT FUNCTION ' only one substring
ELSE
EXIT DO
END IF
ELSE
n=n+1:z=z+LEN(b$)
END IF
LOOP
m=n+1:n=1
DIM SP$(m)
DO
z=INSTR(1,a$,b$)
IF z=0 THEN
SP$(m)=a$:EXIT DO
ELSE
SP$(n)=LEFT$(a$,z-1):a$=MID$(a$,z+LEN(b$)):n=n+1
END IF
LOOP
Split=m
END FUNCTION
See alsoThe
cField$ CFunction extracts individual fields from a string in real-time rather than splitting and you might consider this as it offers advantages of speed and memory over Split() but has some limitations in that an empty string is returned if the delimiter is not found and there is no way of telling the number of substrings.