Older Version Newer Version

bshipps64 bshipps64 Mar 10, 2006 - "First created"

FindReplace$() function

A function that locates the first or all occurrence(s) of string B within string A and replaces it/them with string C.

 orig$ = "This is the original string." 

print orig$
print FindReplace$(orig$, "the", "NOT the", 0)
print : print

orig$ = "one two two four four four FOUR"

print "Original: "; orig$
print
print "Replacing first occurrence of 'four' with 'three'"
print "Replaced: "; FindReplace$(orig$,"four","three",0)
print

f$ = "four"
r$ = "three"
all = 1

print "Replacing all occurrences of 'four' with 'three'"
print "Replaced: "; FindReplace$(orig$, f$, r$, all)
print

print "Replacing all spaces with commas"
print "Replaced: "; FindReplace$(orig$, " ", ",", all)

end

function FindReplace$(origString$,find$,replace$,replaceAll)
'No point doing any work if the original string
'and the 'find' string are blank...
if ((origString$ <> "") and (find$ <> "")) then
'Enter a loop
do
'Get the position of find$ within origString$
fPos = instr(origString$,find$)

'If not found, we're done.
if not(fPos) then
FindReplace$ = origString$
exit function
end if

'Get the length of find$, place everything
'before that in one variable, and everything
'after in another. Set origString$ itself to
'the new value in case all occurrences are
'to be replaced.
fLen = len(find$)
pre$ = left$(origString$, fPos - 1)
post$ = mid$(origString$, fPos + fLen)
origString$ = pre$ + replace$ + post$

loop while replaceAll
FindReplace$ = origString$
end if
end function