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)endfunction 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 loopdo'Get the position of find$ within origString$
fPos =instr(origString$,find$)'If not found, we're done.ifnot(fPos)then
FindReplace$ = origString$
exitfunctionendif'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$
loopwhile replaceAll
FindReplace$ = origString$
endifendfunction
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.