代码之家  ›  专栏  ›  技术社区  ›  magneto

一次多次替换vb6

  •  1
  • magneto  · 技术社区  · 8 年前

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

    我想要的输出是“epplaeppla”

    如果我使用:

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

    但是

    Output will be : "applaappla"
    

    在这种情况下,如果一个替换不受另一个替换的影响,有没有更好的方法来多重替换字母或单词?不仅仅是两次更换的情况,还包括多次更换相互影响的情况。

    1 回复  |  直到 8 年前
        1
  •  2
  •   dbmitch    8 年前

    最安全和最简单的方法是使用两步替换,即临时替换ASCII图表中未使用的字符(在图表顶部-ASCII CODE 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