14.1. Split and splita

[<<<] [>>>]

The commands split and splita split a string into sub-strings. The syntax of the commands are

SPLIT expression BY expression TO variable_list SPLITA expression BY expression TO variable

The first expression on the command is the string to split up. The second expression is the string used to split up the first one. For example

const nl="\n"
split "first,second,third,fourth" by "," to fi,se,th,fo
print fi,nl,se,nl,th,nl,fo

splits the string by the commas and will print

first
second
third
fourth

The resulting sub-strings get into the variables listed after the keyword to. In case of command SPLITA there is only a single variable after the keyword TO. This variable will become an array and the elements of the array will hold the sub-strings. The resulting array will be indexed starting with zero. Thus

splita "first,second,third,fourth" by "," to q
print lbound(q)," ",ubound(q)

will print

0 3

and the sub-strings get into the array q[0], q[1], q[2] and q[3]. In this case the array will have as many elements as need by the split string. If the string to be split is undef the result will also be undef. In this case the variable will not become an array, but remain simple variable holding the value undef.

If there are more variables in a split statement than sub-string the rest of the variables will become undef.

split "q,w,e" by "," to q,w,e,r,t
print r," ",t 

will print

undef undef

If there are less number of variables than sub-strings the last variable will hold the remaining part of the original string holding the separator strings as well. For example:

split "q,w,e" by "," to q,w
print q,"\n",w,"\n"

will print

q
w,e

This way you can write programs that chop off few elements from a string containing some kind of list and leave the rest of the string in a variable. For example:

ListVar = "1,2,3,4,5,6,7,8,9,10,55"
while IsDefined(ListVar)
split ListVar by "," to FirstMember,ListVar
print FirstMember,"\n"
wend 

will print

1
2
3
4
5
6
7
8
9
10
55

If two separator strings follow each other then the resulting sub-string is empty string. For example:

splita "1,,2" by "," to q
for i=lbound(q) to ubound(q)
print q[i],"\n"
next i 

will print

1

2

However separator strings on the start and on the end of the string are ignored:

splita ",1,2,3," by "," to q
for i=lbound(q) to ubound(q)
print q[i],"\n"
next i 

will print

1
2
3

The separator string can be any length, arbitrary string.

After a string is split into sub-string there is a need many times to put the parts together. To do that the string function JOIN can be used.


[<<<] [>>>]