summaryrefslogtreecommitdiff
path: root/bs/string.scm
diff options
context:
space:
mode:
authorBen Sima <ben@bsima.me>2020-05-13 13:32:14 -0700
committerBen Sima <ben@bsima.me>2020-05-13 13:32:14 -0700
commite6ad8129cc854dac38940acb24e3a07cd0cd7b56 (patch)
treedfadd90e9039184e3d1415cdcddfcd39108e9d5c /bs/string.scm
parent5fc1cc6602ac03d05ce004d8d4d9c712242f318b (diff)
Re-namespace general scheme code to bs
Diffstat (limited to 'bs/string.scm')
-rw-r--r--bs/string.scm72
1 files changed, 72 insertions, 0 deletions
diff --git a/bs/string.scm b/bs/string.scm
new file mode 100644
index 0000000..b12bf00
--- /dev/null
+++ b/bs/string.scm
@@ -0,0 +1,72 @@
+(define-module (bs string)
+ #:export (replace replace-char to-string str capitalize split
+ strip lstrip rstrip))
+
+(define (split s c)
+ (if s
+ (string-split s c)
+ #f))
+
+(define (replace-char s match repl)
+ (let ((f (lambda (a b)
+ (let ((next-char (if (eq? a match) repl a)))
+ (string-concatenate (list b (string next-char)))))))
+ (string-fold f "" s)))
+
+(define (replace s match repl)
+ (string-replace-substring s match repl))
+
+(define (to-string x)
+ (format #f "~a" x))
+
+(define str
+ (case-lambda
+ (() "")
+ ((x) (to-string x))
+ ((x . rest) (string-concatenate (map str (cons x rest))))))
+
+(define (capitalize s)
+ (let ((s (to-string s)))
+ (if (< (string-length s) 2)
+ (string-upcase s)
+ (str (string-upcase (substring s 0 1))
+ (substring s 1 )))))
+
+(define (strip s char)
+ (string-trim-both s char))
+
+(define (lstrip s char)
+ (string-trim s char))
+
+(define (rstrip s char)
+ (string-trim-right s char ))
+
+
+;;; {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)))))))))