A simple string replace function

Post Reply
User avatar
Dav
Posts: 279
Joined: Tue Dec 30, 2014 5:12 pm
My devices: iPad Mini, iPod Touch.
Location: North Carolina, USA
Contact:

A simple string replace function

Post by Dav »

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

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

User avatar
Mr. Kibernetik
Site Admin
Posts: 4786
Joined: Mon Nov 19, 2012 10:16 pm
My devices: iPhone, iPad, MacBook
Location: Russia
Flag: Russia

Re: A simple string replace function

Post by Mr. Kibernetik »

Dav wrote:

Code: Select all

'This function assumes OPTION BASE 1
You always can get existing OPTION BASE value with OPTION_BASE() function, then set whatever OPTION BASE you need, and at the end restore old OPTION BASE value with OPTION BASE command (it accepts variables). So your functions will not depend on existing OPTION BASE value.

User avatar
Dav
Posts: 279
Joined: Tue Dec 30, 2014 5:12 pm
My devices: iPad Mini, iPod Touch.
Location: North Carolina, USA
Contact:

Re: A simple string replace function

Post by Dav »

Oh! That's good. I didn't realize that function was there. Thanks!

- Dav

Post Reply