unofficial mirror of guile-user@gnu.org 
 help / color / mirror / Atom feed
* Replacing substrings in strings
@ 2009-04-14 17:18 Sebastian Tennant
  2009-04-14 17:35 ` Linas Vepstas
  2009-04-15  8:52 ` Ludovic Courtès
  0 siblings, 2 replies; 7+ messages in thread
From: Sebastian Tennant @ 2009-04-14 17:18 UTC (permalink / raw)
  To: guile-user

Hi Guilers,

I needed to replace two consecutive spaces in strings with '  ' so
I came up with this:

 (define (replace-substring s t u)
   "Return string S with all occurrences of string T replaced by string U."
   (let ((rv ""))
     (let loop ((r s)) ; r for 'remaining'
       (let ((a 0) (b 0))
         (set! a (string-contains r t)) ;match-start index
         (if a
             (begin
               (set! b (+ a (string-length t))) ;match-end index
               ;; concatenate that which precedes match-start and u to rv
               (set! rv (string-append rv (substring r 0 a) u)) 
               (loop (substring r b))) ;repeat on that which follows match-end
           (set! rv (string-append rv r)))))
     rv))

 (replace-string "Hello.  How are you?" "  " "  ")
 => "Hello.  How are you?"

It works, but seems like a lot of work to achieve something pretty
banal.

At first I thought Richard Todd's (string transform) module in guile-lib
would be able to help, but it works on single characters rather than
substrings.

Are there any there other string libraries I don't know about that could
be used to achieve this?  Or is there a better algorithm for that
matter?  Silly question - of course there is!

Regards,

Seb
-- 
Emacs' AlsaPlayer - Music Without Jolts
Lightweight, full-featured and mindful of your idyllic happiness.
http://home.gna.org/eap





^ permalink raw reply	[flat|nested] 7+ messages in thread

end of thread, other threads:[~2009-05-02  0:29 UTC | newest]

Thread overview: 7+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2009-04-14 17:18 Replacing substrings in strings Sebastian Tennant
2009-04-14 17:35 ` Linas Vepstas
2009-04-15  7:04   ` Sebastian Tennant
2009-05-02  0:29     ` Neil Jerram
2009-04-15  8:52 ` Ludovic Courtès
2009-04-15  9:09   ` Sebastian Tennant
2009-04-15 14:32     ` Ludovic Courtès

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).