Though it hasn't been used in this thread, have you considered that an initial call outside the loop could be done on the original Text string? If it returned zero, you could simply return Text, rather than doing an unnecessary copy to Result.Eclipzer wrote:I only make a single call to INSTR. Most approaches require an initial call outside the loop, with subsequent calls within the loop.
Here's a more efficient implementation. While I've incorporated the above trick, the main difference is that Result gradually builds itself up from newString and chunks of Text, rather than rebuilding itself each time an insertion is made.
Code: Select all
function str_replace( _
byref text as const string, _
byref subString as const string, _
byref newString as const string) as string
if len(text) = 0 then return ""
if len(subString) = 0 then return text
dim as integer match = instr(text, subString), match0 = any
if match = 0 then return text
dim as string result
dim as integer sublen = len(subString), newlen = len(newString)
result = left(text, match - 1) & newstring
match0 = match + sublen
match = instr(match0, text, subString)
if match = 0 then return result & mid(text, match0)
assert( match >= match0 )
result &= mid(text, match0, match - match0)
result &= newString
There's some setting up that Instr has to do, which can technically be eliminated when the only change on each call is that the start value increases monotonically.