Is there a function that exists whcih takes a string and replaces
matching substrings with another given string?
example:
some-string-replace ( "cars and cats" "c" "ch")
returns : "chars and chats"
Thanks.
·········@ptcstudios.com
········@ptcstudios.com wrote:
> Is there a function that exists whcih takes a string and replaces
> matching substrings with another given string?
Did you RTFM? ACL comes with an online version of the ANSI Common Lisp spec.
I'm not aware of such a function, though.
> example:
>
> some-string-replace ( "cars and cats" "c" "ch")
> returns : "chars and chats"
Take a look at the recent thread "Search & replace in sequences"
for ideas on how to implement this.
Michael
--
Michael Kappert
Fraunhofer IITB
Fraunhoferstr. 1 Phone: +49(0)721/6091-477
D-76131 Karlsruhe, Germany EMail: ···@iitb.fhg.de
Michael Kappert <···@iitb.fhg.de> writes:
> > example:
> >
> > some-string-replace ( "cars and cats" "c" "ch")
> > returns : "chars and chats"
>
> Take a look at the recent thread "Search & replace in sequences"
> for ideas on how to implement this.
(defun replace-substrings (string substring replacement)
(declare (optimize (speed 3))
(type simple-string string substring replacement))
(assert (> (length substring) 0) (substring)
"Substring ~A must be of length ~D > 0"
substring (length substring))
(with-output-to-string (stream)
(loop with substring-length = (length substring)
for index = 0 then (+ match-index substring-length)
for match-index = (search substring string :start2 index)
do
(write-string string stream :start index :end match-index)
(when match-index
(write-string replacement stream))
while match-index)))
Note that this isn't in any way a fine-tuned or well optimized
implementation. In implementations with not-so-well performing
string-output-streams, like CMUCL, this might cons a bit more than
doing the allocation in a pre-pass.
Note also that CMUCL has a bug in the version I'm using, which makes
write-string only accept fixnum end parameters, so you'll need to
replace the line
(write-string string stream :start index :end match-index)
with
(write-string string stream :start index :end (or match-index (length string)))
until this bug is fixed (patch is on the way).
Regs, Pierre.
--
Pierre Mai <····@acm.org> PGP and GPG keys at your nearest Keyserver
"One smaller motivation which, in part, stems from altruism is Microsoft-
bashing." [Microsoft memo, see http://www.opensource.org/halloween1.html]