Sysop: | Amessyroom |
---|---|
Location: | Fayetteville, NC |
Users: | 23 |
Nodes: | 6 (0 / 6) |
Uptime: | 52:44:07 |
Calls: | 583 |
Files: | 1,139 |
D/L today: |
179 files (27,921K bytes) |
Messages: | 111,617 |
Any nice way of replacing substrings, i'm currently using below
it works but it's discusting :
(defun substring-replace (new old text )
(let ((res "") (now 0)
(old-length (length old))
(text-length (length text)))
(loop
(if (> (+ now old-length) text-length)
(progn
(if (< now text-length)
(setq res
(concatenate 'string res
(subseq text now))))
(return res))
(if (string= old
(subseq text now (+ now old-length)))
(progn
(setq res
(concatenate 'string res new))
(incf now old-length))
(progn
(setq res
(concatenate 'string res
(subseq text now (1+ now))))
(incf now)))))))
fireblade wrote:
Any nice way of replacing substrings, i'm currently using below
it works but it's discusting :
(defun substring-replace (new old text )
(let ((res "") (now 0)
(old-length (length old))
(text-length (length text)))
(loop
(if (> (+ now old-length) text-length)
(progn
(if (< now text-length)
(setq res
(concatenate 'string res
(subseq text now))))
(return res))
(if (string= old
(subseq text now (+ now old-length)))
(progn
(setq res
(concatenate 'string res new))
(incf now old-length))
(progn
(setq res
(concatenate 'string res
(subseq text now (1+ now))))
(incf now)))))))
Gauche Scheme
(use srfi-13) ;; String functions.
(define (gsub old new text :optional (start 0) (accum '()))
(let1 p (string-contains text old start)
(if p
(gsub old new text
(+ p (string-length old))
(cons* new (string-copy text start p) accum))
(string-concatenate
(reverse (cons (string-copy text start) accum))))))
If the function "string-contains" isn't available,
this can be used.
(define (string-contains text str :optional (start 0))
(let1 len-str (string-length str)
(do ((i start (+ i 1))
(end (- (string-length text) len-str))
(found #f
(if (string= str (substring text i (+ i len-str)))
i #f)))
((or found (> i end)) found))))