2005-11-25

Notes - Lotus Script: Replace Substring

Function ReplaceSubstring(sourcestr As String, fromstr As String, tostr As String) As String
   ' This function replaces characters in a string. Take all the occurrences of "fromstr"
   ' in the source string and replace them with "tostr"
   Dim tempstr As String
   Dim convstr As String
   Dim i As Long
   Dim length As Long
   tempstr = sourcestr
   If Len(fromstr) = 0 Then
      ReplaceSubstring = sourcestr
      Exit Function
   End If
   If Instr(tostr, fromstr) <> 0 Then ' If, for example, "\" is being replaced with "\\"
      ' Find a character (or set) that is not in the source string.
      ' Try the extended characters (over 128 ASCII)
      i = 128
      length = 1
      convstr = ""
      While convstr = ""
         If Instr(tempstr, String$(length, Chr$(i))) = 0 Then convstr = String$(length, Chr$(i))
         i = i + 1
         If i = 256 Then ' If all the extended characters were in there
            length = length + 1 ' Start over, but try 2 extended characters (or 3 or 4)
            i = 128
         End If
      Wend
      ' Go through tempstr twice - once replacing fromstr with the computed
      ' string, then replacing the computed string with tostr
      While Instr(tempstr, fromstr) <> 0
         tempstr = Left(tempstr, Instr(tempstr, fromstr)-1) & convstr _
         & Mid(tempstr, Instr(tempstr, fromstr)+Len(fromstr))
      Wend
      While Instr(tempstr, convstr) <> 0
         tempstr = Left(tempstr, Instr(tempstr, convstr)-1) & tostr _
         & Mid(tempstr, Instr(tempstr, convstr)+Len(convstr))
      Wend
   Else ' It's a normal replace substring call - fromstr is not part of tostr
      While Instr(tempstr, fromstr) <> 0
         tempstr = Left(tempstr, Instr(tempstr, fromstr)-1) & tostr _
         & Mid(tempstr, Instr(tempstr, fromstr)+Len(fromstr))
      Wend
   End If
   ReplaceSubstring = tempstr
End Function

1 comment:

  1. This works perfect. Just what I needed to complete my script!

    ReplyDelete