Skip to content

Instantly share code, notes, and snippets.

@ArneBab
Created July 9, 2018 00:52
Show Gist options
  • Save ArneBab/15fff6243e819ff0ed61ceac12d3b5d5 to your computer and use it in GitHub Desktop.
Save ArneBab/15fff6243e819ff0ed61ceac12d3b5d5 to your computer and use it in GitHub Desktop.
(define* (string-replace-substring s substr replacement #:optional (start 0) (end (string-length s)))
"Replace every instance of substring in s by replacement."
(let ((substr-length (string-length substr)))
(if (zero? substr-length)
(error "string-replace-substring: empty substr")
(let loop
((start start)
(pieces (list (substring s 0 start))))
(let ((idx (string-contains s substr start end)))
(if idx
(loop (+ idx substr-length)
(cons* replacement
(substring s start idx)
pieces))
(string-concatenate-reverse
(cons (substring s start)
pieces))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment