Replace multiple substrings within a string - error in function

emaduddeen

Well-known member
Joined
May 5, 2010
Messages
171
Location
Lowell, MA & Occasionally Indonesia
Programming Experience
Beginner
Hi Everyone,

I found this function that replaces multiple substrings within a string on the internet but it gives an error on one of the parameters.

It doesn't like this one:

VB.NET:
ByVal ParamArray FindChars()) As String

Can you look at the code and correct the error since I don't yet know about explicitly typed parameters?

Thanks.

Truly,
Emad

VB.NET:
    Public Function ReplaceMultiple(ByVal OrigString As String, _
         ByVal ReplaceString As String, ByVal ParamArray FindChars()) _
         As String

        '*********************************************************
        'PURPOSE: Replaces multiple substrings in a string with the
        'character or string specified by ReplaceString

        'PARAMETERS: OrigString -- The string to replace characters in
        '            ReplaceString -- The replacement string
        '            FindChars -- comma-delimited list of
        '                 strings to replace with ReplaceString
        '
        'RETURNS:    The String with all instances of all the strings
        '            in FindChars replaced with Replace String
        'EXAMPLE:    s= ReplaceMultiple("H;*()ello", "", ";", ",", "*", "(", ")") -
        'Returns Hello
        'CAUTIONS:   'Overlap Between Characters in ReplaceString and 
        '             FindChars Will cause this function to behave 
        '             incorrectly unless you are careful about the 
        '             order of strings in FindChars
        '***************************************************************

        Dim lLBound As Long
        Dim lUBound As Long
        Dim lCtr As Long
        Dim sAns As String

        lLBound = LBound(FindChars)
        lUBound = UBound(FindChars)

        sAns = OrigString

        For lCtr = lLBound To lUBound
            sAns = Replace(sAns, CStr(FindChars(lCtr)), ReplaceString)
        Next

        ReplaceMultiple = sAns


    End Function
 
VB.Net version:
VB.NET:
Public Function ReplaceMultiple(ByVal input As String, ByVal replace As String, ByVal ParamArray search() As String) As String
    For Each item As String In search
        input = input.Replace(item, replace)
    Next
    Return input
End Function
 
Regex.Replace(input, String.Join(findArray, "|"), replaceWith)
It wouldn't work with the sample without first escaping all special chars:
'EXAMPLE: s= ReplaceMultiple("H;*()ello", "", ";", ",", "*", "(", ")")
String.Join parameters is also (separator, value).
 
Back
Top