Page History: SPLIT Function (VB work-a-like)
Compare Page Revisions
Page Revision: 2018/11/05 13:00
The Split function breaks a delimited 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.
NOTE: The sub-strings are always returned in the array SP$, 1 is the first sub-string. Trashes previous content of SP$ and the original passed in string (save it before the call if you are likely to need it)
A
similar function extracts individual fields from a string in real-time rather than splitting and you might consider this as it offers advantages over the below (speed, memory, destruction of the original string).
Commonly, after a Split() in VB, one uses the UBound() function to determine the number of substrings. MMbasic does not have UBound but the Split function below reports the number of elements and reports back 1 element - with SP(1) as the entire string - if the delimiter is not found.
Substrings are not trimmed.
Delimiter can be any length>0
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