A simple string replace function
Posted: Tue Jan 27, 2015 2:52 am
I needed a simple string replace function and made this. It can replace part of a string with another one. It is very basic but suited my needs. Thought I would share it here. It can replace the first found string only, or you can do/until to change them all.
- Dav
- Dav
Code: Select all
'Replace$.txt
'Simple string replace funtion.
'Very basic.
'by Dav
OPTION BASE 1
'A test string to use
A$ = "This is bad. I'm having a bad, bad day."
print A$
print
'Replace only first bad with good
'(match case set)
A$ = Replace$(A$, "bad", "good", 1)
print A$
print
'Here's how to Replace in the entire string
'(don't match case)
do
B$ = Replace$(A$, "BaD", "good", 0)
if B$ = A$ then break
A$ = B$
until forever
print A$
End
DEF Replace$(Str$, Find$, New$, case)
'
'This is a string replace function.
'It replaces only FIRST occurence of a string
'with another one. Can Match case if desired.
'If no match found, function returns Str$
'This function assumes OPTION BASE 1
'
'Str$ is the string to use
'Find$ is the part you want to replace
'New$ is what you want to replace it with
'case is if to match case or not.
'(if case = 1 then match case)
t$ =""
'find 1st occurence location
if case = 1 then 'match case
A = INSTR(Str$, Find$, 1)
else
A = INSTR(capstr$(Str$), capstr$(Find$), 1)
end if
'get length of text to remove
L = LEN(Find$)
'if found one
if A <>-1 then
'get before text, add new text
t$ = MID$(Str$, 1, A - 1) & New$
'add the after stuff to that
t$ = t$ & MID$(Str$, A + L, LEN(Str$) - L)
end if
'if we didn't change anything, return original
if t$ = "" then
Replace$ = Str$
else ' if we changed, return changed text
Replace$ = t$
end if
END DEF