Search code examples
vbavb6

Multi-Replace at once vb6


Suppose I have a string "appleapple". I want to replace all 'a' by 'e' and all 'e' by 'a' in vb6.

My desired output is "epplaeppla"

If I use:

str = "appleapple"
str = Replace(str, "a", "e")
str = Replace(str, "e", "a")

But

Output will be : "applaappla"

Is there any better way to multi-replace letters or words where one replacement is not affected by another like in this type of case? Not just for the case of two replacements but say for multiple cases where many replacements affect one another.


Solution

  • The safest and easiest way is to use a two step replacement where you temporarily substitute unused characters in the ASCII chart (at the top of the chart - ASCII CODEs 0 - 31) and then replace those with your final choices.

    See Full ASCII Chart

    See image below for sample of typically unused chars

    Unused ASCII characters

    This should work for single character as well as multiple char replacements.

    Option Explicit
    
    ' Use this to distinguish between upper and lower case replacements
    Option Compare Binary
    
    Public Sub SafeMultiReplace()
    
        ' use something not in list of characters being searched or replaced
        Const DELIM         As String = ","
    
        Const START_STRING  As String = "appleappleAPPLE"
    
        Dim ReplaceString   As String
        Dim OutputString    As String
    
        Dim ChangeVars      As Variant
        Dim ReplaceVars     As Variant
    
        Dim i               As Integer
    
        ' These two arrays must match total vars
        ' Load array of many characters you want to change From
        ChangeVars = Split("a,e", DELIM)
    
        ' Load array of many characters you want to change to
        ReplaceVars = Split("e,a", DELIM)
    
        OutputString = START_STRING
    
        ' Replace original chars with unused chars
        For i = LBound(ChangeVars) To UBound(ChangeVars)
            OutputString = Replace(OutputString, ChangeVars(i), Chr(i))
        Next i
    
        ' Replace unused chars with replacement chars
        For i = LBound(ReplaceVars) To UBound(ReplaceVars)
            OutputString = Replace(OutputString, Chr(i), ReplaceVars(i))
        Next i
    
        Debug.Print "Final Output: " & OutputString
        'Final Output: epplaepplaAPPLE
    
    End Sub