SplitToArray keeping empty positions

Started by Mahan, July 27, 2010, 04:30:09 AM

Previous topic - Next topic

Mahan

I wrote a little replacement function for the SplitToArray command, since I didn't like the way it "forgot" empty fields in the original string.
Often when parsing a CSV of some sort, empty fields are significant and the "column number" of a field must be the same regardless of previous fields being filled or empty.

By commenting/uncommenting with the various example strings in the example program you can see the difference.

(for PlayBasic 1.64L)

PlayBASIC Code: [Select]
Explicit on

local test$
test$=",,..,,,,5"
//test$=""
//test$=","
//test$=",,1"
//test$=",1,2,3,,5"

local i, count

print "With original SplitToArray:"
dim args$(0)
count=SplitToArray(test$, ",", args$(), 1)
print "Count: " + str$(count)
for i = 1 to count
print "args$(" + str$(i) + ") = " + args$(i)
next

print "With SplitToArray2() function:"
dim args$(0)
count=SplitToArray2(test$, ",", args$())
print "Count: " + str$(count)
for i = 1 to count
print "args$(" + str$(i) + ") = " + args$(i)
next


sync
WaitKey


function splitToArray2(s$, d$, res$())
local cellCount = 0
redim res$(cellCount)
local pp = 1
local p = InString(s$, d$, 1, false)
While (p<>0)
inc cellCount
redim res$(cellCount)
res$(cellCount) = mid$(s$, pp, p-pp)
pp = p + len(d$)
local p = InString(s$, d$, pp, false)
EndWhile
inc cellCount
redim res$(cellCount)
res$(cellCount) = mid$(s$, pp, len(s$))
EndFunction cellCount





  ModEdit: PlayBASIC revisions above V1.64M, have flags that to this with the build in SplitToArray command