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

string-replace!

This page is part of the web mail archives of SRFI 13 from before July 7th, 2015. The new archives for SRFI 13 contain all messages, not just those from before July 7th, 2015.



Should have specified string-replace!, the destructive counterpart to
string-replace.  Also a minor change to string-copy!; my implementation now
makes the endpoints optional.

; replacement, destructive version
; reuses storage of s1 if the result is not longer than s1
; returns the new version of s1, whether storage is reused
(define (string-replace! s1 start end s2)
  (if (> (string-length s2) (- end start))
      (string-replace s1 start end s2)
      (begin
        ; copy s2 into s1 starting at start
        (string-copy! s1 start s2 0 (string-length s2))
        ; the next line depends on string-copy! copying chars in ascending
order
        (string-copy! s1 (+ start (string-length s2)) s1 end (string-length
s1))
        ; the return value:  if string length has changed, should return a
        ; shared substring
        (if (= (string-length s2) (- end start))
            s1
            (substring s1 0 (+ (string-length s1) (- start end)
(string-length s2)))))))

; string-copy!, needed for efficient version of replacement
(define (string-copy! target tstart s . endpoints)
  (let ((start 0)
        (end (string-length s)))
    (if (not (null? endpoints))
        (begin
          (set! start (car endpoints))
          (set! end (cadr endpoints))))
    (do ((i tstart (+ i 1))
         (j start (+ j 1)))
      ((= j end) 'ok)
      (string-set! target i (string-ref s j)))))