Split char-delimited strings
By: Lorenzo Dalla Vecchia Date: 21/06/2000

Very often, programs need to "split" a string in multiple parts, looking for a particular delimiter between them; this delimiter can be a comma (,), a pipe (|), a space, etc.
Two uses of string-splitting are to determine the parameters entered after your EXE file name (space-delimited) or to extract the names of multiple files selected with an Open dialog box (pipe-delimited).

Microsoft added a great function to version 6 of Visual Basic: the Split function. The Split function does all the work automatically, so if you have VB6, there should be no problems. The syntax for the Split function is the following:

Dim array() As String
array = Split(string, delimiter)

array is a dynamic-array (no index specified) to hold the "pieces" resulting from the split operation; the array must be dynamic because you don't know how many "pieces" there are. string is the string to be splitted, delimiter is a short string with the delimitation character(s).

A little example, let's see how to split parameters retrieved from the EXE file with the Command function; remember they are space-delimited:

Dim Parameters() As String
Parameters = Split(Command, " ")

To access the array (wich is 0-based) ...

Parameters(0)
Parameters(1)
Parameters(2)
...

Simple as that. But for VB versions older than 6.0?
The following code will work with any VB version.

Dim array() As String
Dim n As Integer
Dim chunck As String

Dim BigString As String

ReDim array(0)
For n = 1 To Len(string)
    If Mid(
string, n, 1) = delimiter Then
       
array(UBound(array)) = chunck
        ReDim Preserve
array(UBound(array) + 1)
        chunck = ""
    Else
        chunck = chunck & Mid(
string, n, 1)
    End If
Next n
array(UBound(array)) = chunck

As with the Split function, replace array, string and delimiter with correct values. The final array is accessed in the same way.

Click Here!


Visual Basic Programming Zone is a website by Lorenzo Dalla Vecchia.
To contact the Webmaster, click here.
Hosted by InWind: www.inwind.it