FF_REPLACE and FF_REPLACEANY

Started by Paul Squires, August 19, 2015, 01:36:21 PM

Previous topic - Next topic

Paul Squires




''
''  FF_REPLACE
''  Within a specified string, replace all occurrences of one string with another string.
''
''  Replaces all occurrences of MatchPattern in MainString with ReplaceWith. 
''  The replacement can cause MainString to grow or condense in size.
''  This function is case-sensitive.
''  When a match is found, the scan for the next match begins at the position
''  immediately following the prior match.
''
Function FF_Replace( ByRef sMainString   As String, _
                     ByRef sMatchPattern As String, _
                     ByRef sReplaceWith  As String _
                     ) As String

    Dim i As Integer
    Dim s As String
   
    s = sMainString
    i = 1
    Do
        i = Instr(i, s, sMatchPattern)
        If i > 0 Then
           s = Left(s, i - 1) & sReplaceWith & Mid(s, i + Len(sMatchPattern))
           i += Len(sReplaceWith)
        End If   
    Loop Until i = 0
   
    Return s

End Function


''
''  FF_REPLACEANY
''  Within a specified string, replace all occurrences of any of the individual characters
''  specified in the MatchPattern string.
''
''  This function is case-sensitive.     
''  sReplaceWidth must be a single character. This function does not replace words therefore
''  MainString will be the same size - it will not shrink or grow.
''
Function FF_ReplaceAny( ByRef sMainString   As String, _
                        ByRef sMatchPattern As String, _
                        ByRef sReplaceWith  As String _
                        ) As String

    Dim nLenMain    As Integer = Len(sMainString)
    Dim nLenMatch   As Integer = Len(sMatchPattern)
    Dim nLenReplace As Integer = Len(sReplaceWith)
   
    Dim s As String   
    Dim y As Integer
    Dim i As Integer

    ' Note: sReplaceWith must be one character in size because this function
    '       replaces individual characters rather than words.
    If nLenReplace <> 1 Then Return sMainString
    If nLenMain  = 0 Then Return sMainString
    If nLenMatch = 0 Then Return sMainString
   
    s = sMainString   ' make a default return copy of the string
   
    ' Get each character in the sMatchPattern string and look for it in sMainString
    ' Using string pointer indexing for speed.
    For y = 0 To nLenMatch - 1
       For i = 0 To nLenMain - 1
          If sMatchPattern[y] = sMainString[i] Then
             s[i] = sReplaceWith[0]
          End If
       Next
    Next
   
    Function =  s

End Function


Paul Squires
PlanetSquires Software