replace=: 4 : 0
'p q'=. y
j=. p [EMAIL PROTECTED] x
if. ''-:j do. x return. end.
select. *d=. p -&# q
case. 1 do. (0 (j+/q(}.i.)&#p)}1$~#x) # q (j +/ i.#q)}x
case. 0 do. q (j +/ i.#p)}x
case. _1 do. q k} (0 (d{."1 k)}1$~(#x)+(#j)*|d) #^:_1 x [ k=.
(j+(|d)*i.#j)+/i.#q
end.
)
----- Original Message -----
From: Roger Hui <[EMAIL PROTECTED]>
Date: Thursday, November 13, 2008 13:31
Subject: Re: [Jprogramming] tacit stringreplace
To: Programming forum <[email protected]>
> "replace0" can be improved by
> - having a special case where the old and new strings
> have the same length.
> - use expand/amend rather than cut/raze when the
> old string is shorter than the new string.
> Thus:
>
> ff=: {: a.
>
> NB. x is text; y is (p;q); replace all occurrences of p by q in x
> replace0=: 4 : 0
> 'p q'=. y
> d=. p -&# q
> b=. p E. x
> if. 0<:d do. NB. replacement
> string not longer
> ff -.~ (q,d$ff) ((I. b) +/ i.#p)}x
> else. NB. replacement string longer
> ((b i. 1){.x) , ; q&,&.>(#p)}.&.>b <;.1 x
> end.
> )
>
> replace=: 4 : 0
> 'p q'=. y
> j=. p [EMAIL PROTECTED] x
> if. ''-:j do. x return. end.
> select. *d=. p -&# q
> case. 1 do. ff -.~ (q,d$ff) (j +/ i.#p)}x
> case. 0
> do. q (j +/ i.#p)}x
> case. _1 do. q k} (0 (d{."1 k)}1$~(#x)+(#j)*|d) #^:_1 x [
> k=. (j+(|d)*i.#j)+/i.#q
> end.
> )
>
> x=: 1e6 $ 'of the people, by the people, for the
> people; '
> ts=: 6!:2 , 7!:[EMAIL PROTECTED]
>
> ts 'x replace0 y' [ y=: 'people';'rich'
> 0.0668616 6.55693e6
> ts 'x replace y'
> 0.063969 5.50886e6
>
> ts 'x replace0 y' [ y=: 'the';'one'
> 0.0647373 4.46042e6
> ts 'x replace y'
> 0.0338585 3.41133e6
>
> ts 'x replace0 y' [ y=: 'the';'them there'
> 0.129838 2.79676e7
> ts 'x replace y'
> 0.0677608 1.99288e7
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm