Visual Basic 6 function "str_split"

Go back

Below you'll find the source for the Visual Basic 6 function str_split.

Attribute VB_Name = "modStrSplit"
' This function is downloaded from:
' http://www.stefanthoolen.nl/archive/vb6-functions/
' 
' You may freely distribute this file but please leave all comments, including this one, in it.
' 
' @Author Stefan Thoolen <mail@stefanthoolen.nl>

Option Explicit

''
' Convert a string to an array
' Same syntax as the PHP function 'str_split'
' See also: http://www.php.net/manual/en/function.str-split.php
' @param    String  str             The string which must be broken
' @param    Integer split_length    The length of each part in characters, default: 1
' @return   Variant                 An array containing all parts
' @author   Stefan Thoolen <mail@stefanthoolen.nl>
Public Function str_split(str As String, Optional split_length As Integer) As Variant
    If Not split_length Then split_length = 1
    
    Dim retval() As Variant, cnt As Integer
    Dim i As Integer, j As Integer, s As String
    For i = 1 To Len(str)
        s = s & Mid(str, i, 1): j = j + 1
        If j = split_length Then
            ReDim Preserve retval(0 To cnt)
            retval(cnt) = s
            cnt = cnt + 1: j = 0: s = ""
        End If
    Next i
    If s <> "" Then
        ReDim Preserve retval(0 To cnt)
        retval(cnt) = s
    End If
    
    str_split = retval
End Function