String Replace *THE FASTEST*

By | 2002-06-01

This code is a direct replacement for the VB6 Replace function. Obviously, VB 6 users will have very little (if any) use for the function. It is intended for use with older versions of VB that do not have the in-built Replace function. I noticed a similar piece of code released earlier this week, but it only appeared to handle character replacing and not strings. This version will do both and it’s pretty tight and fast.

Original Author: Leigh Bowers

Code

Public Function Replace(sExpression As String, sFind As String, sReplace As String) As String
' Title: Replace
' Version: 1.01
' Author: Leigh Bowers
' WWW:  http://www.esheep.freeserve.co.uk/compulsion
Dim lPos As Long
Dim iFindLength As Integer
' Ensure we have all required parameters
If Len(sExpression) = 0 Or Len(sFind) = 0 Then
  Exit Function
End If

' Determine the length of the sFind variable
iFindLength = Len(sFind)

' Find the first instance of sFind

lPos = InStr(sExpression, sFind)

' Process and find all subsequent instances

Do Until lPos = 0
  sExpression = Left$(sExpression, lPos - 1) + sReplace + Mid$(sExpression, lPos + iFindLength)
  lPos = InStr(lPos, sExpression, sFind)
Loop

' Return the result
Replace = sExpression
End Function

Author: dwirch

Derek Wirch is a seasoned IT professional with an impressive career dating back to 1986. He brings a wealth of knowledge and hands-on experience that is invaluable to those embarking on their journey in the tech industry.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.