Write Split and Join functions

Started by nandagopal, Nov 06, 2008, 07:02 PM

Previous topic - Next topic

nandagopal

The VB5Split subroutine chops its input text into pieces. While the input has non-zero length, the program uses InStr to find the next delimiter. If it doesn't find a delimiter, it uses the whole input string as the next array entry. If it finds a delimiter, it adds the next piece to the array and then removes it and the delimiter from the input string.


' Split txt into pieces and return them in an array.
Public Sub VB5Split(ByVal txt As String, ByVal delimiter As _
    String, result() As String)
Dim num_items As Integer
Dim pos As Integer

    num_items = 0
    Do While Len(txt) > 0
        ' Make room for the next piece.
        num_items = num_items + 1
        ReDim Preserve result(1 To num_items)

        ' Find the next piece.
        pos = InStr(txt, delimiter)
        If pos = 0 Then
            ' There are no more delimiters.
            ' Use the rest.
            result(num_items) = txt
            txt = ""
        Else
            ' Use this piece.
            result(num_items) = Mid$(txt, 1, pos - 1)
            txt = Mid$(txt, pos + Len(delimiter))
        End If
    Loop
End Sub


The VB5Join function loops through an array of strings and concatenates them, inserting a delimiter before each entry. This adds a delimiter at the beginning of the string so the code finishes by removing this initial delimiter.


' Join the strings using the delimiter.
Public Function VB5Join(strings() As String, ByVal _
    delimiter As String) As String
Dim i As Integer
Dim result As String

    result = ""
    For i = LBound(strings) To UBound(strings)
        result = result & delimiter & strings(i)
    Next i

    ' Remove the initial delimiter.
    If Len(result) > 0 Then result = Mid$(result, _
        Len(delimiter) + 1)
    VB5Join = result
End Function