bshipps64
Mar 10, 2006
- "Reworked function"
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 "Replacing first occurrence of 'four' with 'three'"
print "Replaced: "; FindReplace$(orig$,"four","three",0)
f$ = "four"
r$ = "three"
all = 1
print "Replacing all occurrences of 'four' with 'three'"
print "Replaced: "; FindReplace$(orig$, f$, r$, all)
print "Replacing all spaces with commas"
print "Replaced: "; FindReplace$(orig$, " ", ",", all)
print : print
orig$ = "aaabbbccc"
print "Original: "; orig$
print "Replacing all occurrences of 'b' with 'bbb'"
print "Replaced: "; FindReplace$(orig$, "b", "bbb", all)
end
functionFindReplace$(origString$,find$,replace$,replaceAll)FindReplace$(FindReplace$,find$,replace$,replaceAll)
'No point doing any work if the original string
'and the 'find' string are blank...
if((origString$((FindReplace$ <> "") and (find$ <> "")) then
'Enter a loop
do
'Get the position of find$ withinorigString$FindReplace$
'starting at previous value of fPos
fPos =instr(origString$,find$,fPos)instr(FindReplace$,find$,fPos)
'If not found, we're done.
if not(fPos) thenFindReplace$ = origString$exit functionend if
'Get the lengths of find$ and replace$, place
'everything before find$ in one variable, and
'everything after it in another. SetorigString$FindReplace$
'itself to the newvalue in case all occurrences'are to be replaced.replaced value. Finally, setthe
'the starting'positionposition for the next iteration ofthe
'the loop equal'toto the start of post$ within thereplaced
'replaced string.
fLen = len(find$)
rLen = len(replace$)
pre$ =left$(origString$,left$(FindReplace$, fPos - 1)
post$ =mid$(origString$,mid$(FindReplace$, fPos + fLen)
origString$FindReplace$ = pre$ + replace$ + post$
fPos = fPos + (rLen - fLen) + 1
loop whilereplaceAllFindReplace$ = origString$(replaceAll)
end if
end function