RE: Replacing characters (Matt: bug)
- Posted by Andy Serpa <renegade at earthling.net> Sep 17, 2002
- 454 views
Derek, Yours fails if "a" is longer than "b"... -- Andy Derek Parnell wrote: > Hi Matt, > unfortunately the algorithm doesn't work. Try this test ... > > x = replace_all2("derekderekderekderek", "rek", "1234567") > > this returns "de1234567derek1234567ekde1234567" > > rather than "de1234567de1234567de1234567de1234567" > > > Anyhow, here is another method of doing it... > > function replace_elem(sequence s, object a, object b) > sequence t > integer n,m > > if atom(a) then > a = {a} > end if > > if atom(b) then > b = {b} > end if > > -- Create a buffer big enough to cater for worst case replacement. > t = repeat(0, (floor(length(s) / length(a)) + 1) * length(b)) > > m = 1 > while 1 do > n = match(a, s) > if n then > t[m..m+n-2] = s[1..n-1] > m += (n-1) > t[m..m+length(b)-1] = b > m += (length(b)) > s = s[n+length(a) .. length(s)] > else > t[m..m+length(s)-1] = s > m += (length(s)) > exit > end if > end while > > return t[1..m-1] > end function > > > ---------------- > cheers, > Derek Parnell > ----- Original Message ----- > From: "Matthew Lewis" <matthewwalkerlewis at YAHOO.COM> > To: "EUforum" <EUforum at topica.com> > Sent: Tuesday, September 17, 2002 9:23 PM > Subject: RE: Replacing characters (Matt: bug) > > > > > From: Dan Moyer [mailto:DANIELMOYER at prodigy.net] > > > > > Matt's now doesn't fail on replace last character, but > > > doesn't actually > > > replace the last character, & is *very* much slower than > > > either of the other > > > two > > > (one test: Henri: 3.9, Andy: 2.75 , Matt: 24.06) ; > > > > It seems to replace the last char when I test it. I believe that the > > slowness is due to the use of subscripting within the call to match(). > > There was some discussion about this recently. I typically run fairly > short > > strings through this routine (maybe 2 or 3 sentence lengths) at a time, > > so > > I've never needed any more speed. > > > > > Henri/Mike "vulcan" routine is faster than Matt's but won't > > > replace one char > > > with 2; > > > > > > Andy's is fastest. How much faster seems to vary. On a > > > "long" sequence to > > > peruse, it seemed twice as fast as Henri/Mike "vulcan", but on many > > > repetitions of replacing in smaller sequence, it seems only > > > 1.4 times faster > > > (see test results above). > > > > Actually, neither one will handle replacements of different lengths. > > This > > was a definite requirement for what I needed, where, for instance you > might > > want to replace "." with "..". Also, neither routine will handle: > > > > R/replace_in_string("abc cba", "ab", "12" ) > > > > Both return "12c c21", which is fine if you've got a cipher (did anyone > use > > this method in the contest? :), but not if you're trying to replace > > words > > with other words, in which case you end up with garbage. Henri talks <snip>