多次替换vb6

时间:2016-09-04 11:06:46

标签: vba vb6

假设我有一个字符串“appleapple”。 我想用'e'替换所有'a',用vb6中的'a'替换所有'e'。

我想要的输出是“epplaeppla”

如果我使用:

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

但是

Output will be : "applaappla"

有没有更好的方法来替换一个替换不受另一个替换的字母或单词,就像在这种情况下一样?不仅仅是针对两个替代品的情况,而是针对多个替代品相互影响的多个案例。

1 个答案:

答案 0 :(得分:2)

最安全,最简单的方法是使用两步替换,暂时替换ASCII图表中的未使用字符(位于图表顶部 - ASCII CODEs 0 - 31),然后用最终选择替换它们。

请参阅Full ASCII Chart

请参阅下面的图片,了解通常未使用的字符的样本

Unused ASCII characters

这适用于单个字符以及多个字符替换。

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