Replace


Description:
This function replaces a token with another token in a string. It's should act just like VB6's Replace() function, and I wrote it to be able to have the same functionality in VB5.

12/29/1999: Fixed a small bug that was causing problems if the replacement was an empty string and the token occurred next to itself.
 
Code:
Public Function Replace(sIn As String, sOld As String, sNew As String) _
       As String
    
    If sIn = "" Then
        Exit Function
    End If
    
    If sOld = "" Then
        Exit Function
    End If
    
    Dim colBefore As Collection
    Set colBefore = New Collection
    
    Dim nPos As Long
    Dim nPosLast As Long
    Dim nLen As Long
    Dim vItem As Variant
    
    nPosLast = 1
    nPos = InStr(nPosLast, sIn, sOld)
    Do While nPos <> 0
        colBefore.Add Mid(sIn, nPosLast, (nPos) - nPosLast)
        nPosLast = nPos + Len(sOld)
        nPos = InStr(nPosLast, sIn, sOld)
    Loop
    
    Replace = Space(Len(sIn) + ((Len(sNew) - Len(sOld)) * _
            colBefore.Count))
            
    nPos = 1
    For Each vItem In colBefore
        nLen = Len(vItem)
        If nLen > 0 Then
            Mid(Replace, nPos, nLen) = vItem
            nPos = nPos + nLen
        End If
        If sNew <> "" Then
            Mid(Replace, nPos, Len(sNew)) = sNew
            nPos = nPos + Len(sNew)
        End If
    Next
    If nPosLast <= Len(sIn) Then
        Mid(Replace, nPos) = Mid(sIn, nPosLast)
    End If
    
    Set colBefore = Nothing
    
End Function
 
Sample Usage:
 
Debug.Print Replace("This is a simple test","simple","short")