SplitString() to split a string by a delimiter into an array
Posted: Tue Aug 14, 2007 8:22 am
There was a request for splitting strings into parts in the wishlist section,
so I wrote this little procedure:
It will be a little slower than StringField() for strings that only contains one or two fields,
but it is much faster for more parts and longer strings.
Happy coding
technicorn
Edit:
For more speed gain you can remove the "ReDim sa.s(splitCnt - 1)" at the end,
than this Proc. is twice as fast as StringField() even for strings with only one part!
The littel memory overhead for empty strings is worth it, I think.
so I wrote this little procedure:
Code: Select all
; Splitting a string into parts
;
; *s = Pointer to string to split
; sa() = String-array which will contain the parts
; delimiter = Character by which the string will be splitted
;
; Returns the number of parts
;
; If the string is empty, sa() will not be changed
; and the return value is 0
Procedure.l SplitString(*s.Character, sa.s(1), delimiter.c)
Protected saUBound.l = 15, splitCnt.l, *splitStart.c, ch.c
If *s
If *s\c
ReDim sa.s(saUBound)
Repeat
*splitStart = *s
ch = *s\c
While ch And ch <> delimiter
*s + SizeOf(Character)
ch = *s\c
Wend
If splitCnt > saUBound
saUBound + 16
ReDim sa.s(saUBound)
EndIf
sa(splitCnt) = PeekS(*splitStart, *s - *splitStart)
splitCnt + 1
*s + SizeOf(Character)
Until Not ch
ReDim sa.s(splitCnt - 1)
EndIf
EndIf
ProcedureReturn splitCnt
EndProcedure
but it is much faster for more parts and longer strings.
Happy coding
technicorn
Edit:
For more speed gain you can remove the "ReDim sa.s(splitCnt - 1)" at the end,
than this Proc. is twice as fast as StringField() even for strings with only one part!
The littel memory overhead for empty strings is worth it, I think.