Splitstr2() split the way the universe meant it to be :-)

Previous topic - Next topic

Moru

Simple splitting function that splits strings the way expected from PHP and similar languages.

splitstr(";a;b;;d;", array[], ";")
gives:
0 = ""
1 = "a"
2 = "b"
3 = ""
4 = "d"
5 = ""


Code (glbasic) Select
// Splits strings into an array, does not skip empty fields or split-characters as first/last on a line
// Considers double split-characters as an empty field ("a;b;;d") = four fields
FUNCTION splitstr2: string$, array$[], split$
LOCAL a$, n, length, found
REDIM array$[0] // Empty the array

length = LEN(string$)

WHILE n<=length
found = INSTR(string$, split$, n) // Find next delimiter

IF found>=0
a$ = MID$(string$, n, found-n) // Find the data
DIMPUSH array$[], a$ // Add it to the field in the array
n = found+1 // Next field
ELSE
a$ = MID$(string$, n, -1) // Find the data
DIMPUSH array$[], a$ // Last field, add to the array
n=length+1
ENDIF
WEND
RETURN LEN(array$[])
ENDFUNCTION

Quentin

was already done before :)
http://www.glbasic.com/forum/index.php?topic=2398.0
I noticed that this routine could work faster if checking the number of needed entries first and then use only one DIM instead of DIMPUSH

Moru

This was created not for speed but for easy to read and use. Since it will not split many per line, the file IO is a lot more than the little time it takes to fill an array. As for the routine already existing, this is what you get from not asking the boards first :-) Now when I see it I remember seeing it when it was first put up there. Well, now we have two different solutions to the problem :-)