summaryrefslogtreecommitdiff
path: root/module/ice-9/string-fun.scm
diff options
context:
space:
mode:
authorDaniel Llorens <lloda@sarc.name>2020-01-06 09:44:01 +0100
committerDaniel Llorens <lloda@sarc.name>2020-01-06 09:44:01 +0100
commit6cfee365434ca8a18053600575c79dde6775bc2d (patch)
tree8e62ccc325405eb37970695f6f657422c053394e /module/ice-9/string-fun.scm
parentddad8ae05adfdb84ef80cb2d2730e73f4d27c74b (diff)
downloadguile-6cfee365434ca8a18053600575c79dde6775bc2d.tar.gz
New function string-replace-substring in (ice-9 string-fun)
By A. Wingo in https://lists.gnu.org/archive/html/guile-devel/2014-03/msg00058.html. * module/ice-9/string-fun.scm (string-replace-substring): As stated. * doc/ref/api-data.texi: Document the new function. * test-suite/tests/strings.test: Test.
Diffstat (limited to 'module/ice-9/string-fun.scm')
-rw-r--r--module/ice-9/string-fun.scm37
1 files changed, 36 insertions, 1 deletions
diff --git a/module/ice-9/string-fun.scm b/module/ice-9/string-fun.scm
index c27ff847f..03e0238fa 100644
--- a/module/ice-9/string-fun.scm
+++ b/module/ice-9/string-fun.scm
@@ -25,13 +25,17 @@
separate-fields-discarding-char separate-fields-after-char
separate-fields-before-char string-prefix-predicate string-prefix=?
sans-surrounding-whitespace sans-trailing-whitespace
- sans-leading-whitespace sans-final-newline has-trailing-newline?))
+ sans-leading-whitespace sans-final-newline has-trailing-newline?
+ string-replace-substring))
;;;;
;;;
;;; Various string funcitons, particularly those that take
;;; advantage of the "shared substring" capability.
+;;; FIXME Document these functions in Miscellaneous String Operations::
+;;; in doc/ref/api-data.texi.
;;;
+
;;; {String Fun: Dividing Strings Into Fields}
;;;
@@ -278,3 +282,34 @@
;;; (fail parts)
;;; (apply return parts))))
+
+
+;;; {String Fun: string-replace-substring}
+;;;
+
+;; string-replace-substring By A. Wingo in
+;; https://lists.gnu.org/archive/html/guile-devel/2014-03/msg00058.html
+;; also in string-replace-substring guix:guix/utils.scm.
+
+(define (string-replace-substring str substring replacement)
+ "Return a new string where every instance of @var{substring} in string
+ @var{str} has been replaced by @var{replacement}. For example:
+
+ @lisp
+ (string-replace-substring \"a ring of strings\" \"ring\" \"rut\")
+ @result{} \"a rut of struts\"
+ @end lisp
+ "
+ (let ((sublen (string-length substring)))
+ (with-output-to-string
+ (lambda ()
+ (let lp ((start 0))
+ (cond
+ ((string-contains str substring start)
+ => (lambda (end)
+ (display (substring/shared str start end))
+ (display replacement)
+ (lp (+ end sublen))))
+ (else
+ (display (substring/shared str start)))))))))
+