After some more considerations I have once again updated the plainest most straight forward replace function with this:
Beeps can be just as annoying as the program halting (like div by 0) if there is a problem causing argument.
I like MID$() because it's no problem when the arguments don't fit the source string.
Also now only make one call for LEN(replace$) and LEN(new$), a little more efficient for really long strings with lots of replacing.
_TITLE "strReplace$ test" 'b+ 2019-12-28 check to see that new l's don't get more replacements ' mod 2020-07-26 check for string lengths on source$ and replace$ but replacement new$ can be ""
' mod 2020-07-27 don't set strReplace$ = s$ because could cause unintented recursion.
' mod 2020-07-28 no beep, just return s$ if s$ or replace$ are 0 length
' also make variable "constants for lengths of replace and new to avoid multiple calls to LEN()
PRINT strReplace$
("hello all", "ll", "l") PRINT strReplace$
("hello all", "l", "lllll") PRINT strReplace$
("lots of luck", "l", "lllll") PRINT strReplace$
("Hello all", "ll", "") 'test a couple of deletions PRINT strReplace$
("l Hello all", "l", "") ' PRINT strReplace$
("", "l", "no source") 'test error conditions PRINT strReplace$
("source no replace", "", "new") 'test error conditions PRINT strReplace$
("", "", "no source or replace") 'test error conditions
FUNCTION strReplace$
(s$
, replace$
, new$
) 'case sensitive 2020-07-28 version LR
= LEN(replace$
): lNew
= LEN(new$
)
sCopy$ = s$ ' otherwise s$ would get changed
p
= INSTR(sCopy$
, replace$
) sCopy$
= MID$(sCopy$
, 1, p
- 1) + new$
+ MID$(sCopy$
, p
+ LR
) p
= INSTR(p
+ lNew
, sCopy$
, replace$
) strReplace$ = sCopy$
You can read the function name as String Replace or Straight Replace, no Swiss Army knife here!