bshipps64 bshipps64 Mar 10, 2006 - "Corrected logic"

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.

  • This function works by taking as input an original string, a 'find' string, a 'replace' string,and either a 0 to specify single occurrence or 1 for all occurrences. It locates the position of 'find' within the original, assigns everything prior to 'find' to one variable, everything after to another, and then it modifies the original string to contain the value of 'replace' inbetween the before and after portions. If a 1 is specified for the replaceAll parameter, the function will loop until 'find' is no longer found in the modified original string. Test program included. This function is a variation of the StringChop$() function , which can be simulated here by specifying a blank 'replace' string and passing 1 for replaceAll.
 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)
print : print

orig$ = "aaabbbccc"

print "Original: "; orig$
print
print "Replacing all occurrences of 'b' with 'bbb'"
print "Replaced: "; FindReplace$(orig$, "b", "bbb", 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$) 'starting at previous value of fPos
fPos = instr(origString$,find$,fPos)

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

'Get the length of find$, lengths of find$ and replace$, place everything 'before that
'everything before find$ in one variable, and everything 'after
'everything after it in another. Set origString$ itself to 'the
'itself to the new value in case all occurrences are 'to
'are to be replaced. Finally, set the starting
'position for the next iteration of the loop equal
'to the start of post$ within the replaced string.
fLen = len(find$)
rLen = len(replace$)
pre$ = left$(origString$, fPos - 1)
post$ = mid$(origString$, fPos + fLen)
origString$ = pre$ + replace$ + post$
fPos = fPos + (rLen - fLen) + 1

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