[comp.sys.handhelds] Search and replace 2

apdoo@alice.UUCP (Alan Weiss) (03/20/90)

The posting by Robert Thompson on how to make a global search and
replace function was very interesting, especially as it used many
SYSEVALs I had never seen.  You may be surprised that I have a
search and replace function that is faster than his, and uses no
SYSEVALs at all!  Perhaps the combination of my algorithm with his
SYSEVALs would be the fastest yet?  Also, with FAST and the note
at the end of this post, you should be able to get a factor of 3
improvement over my program quite easily.

Benchmarks: CHR 0 to "V" in a STR-> string: his 92 sec, mine 80 sec
            Replace a string of 10 "Z" characters with 10 "U" chars:
                                            his 1.6 sec, mine .97 sec
The new and old substrings do not have to be the same length; indeed,
the biggest use I have for this program is stripping out newline
characters and replacing them with empty strings.

CHG [checksum A781]
3: String to change
2: Old substring      ----->
1: New substring              1:Changed string

<< -> x y
  <<
    << DUP
       IF x POS DUP
       THEN DUP2 1 -
1 SWAP SUB 3 ROLLD 1
+ OVER SIZE SUB y
SWAP + +
       ELSE DROP
       END
    >> MULTI
  >>
>>

If you leave out the third << and MULTI, the program replaces one
instance of the old substring with the new, and MULTI does any
program repeatedly until the result doesn't change.  I'm sure you
can hack with this until it is much faster, by writing an outer loop
with "x POS", but I actually use the one at a time replacement, so
leave it with or without MULTI as the case has it.  For completeness,
here's MULTI:

MULTI (from the owner's manual) [8098]
<< -> p << DO DUP p
EVAL UNTIL DUP ROT
SAME END >> >>

Alan Weiss, AT&T Bell Labs    inet!research.att.com!apdoo