[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Replacing substrings in strings

From: Sebastian Tennant
Subject: Replacing substrings in strings
Date: Tue, 14 Apr 2009 17:18:03 +0000
User-agent: Gnus/5.110011 (No Gnus v0.11) Emacs/22.2 (gnu/linux)

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
               (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)))))

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

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

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

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!


Emacs' AlsaPlayer - Music Without Jolts
Lightweight, full-featured and mindful of your idyllic happiness.

reply via email to

[Prev in Thread] Current Thread [Next in Thread]