summaryrefslogtreecommitdiff
path: root/Alpha/String.scm
blob: c7ad61fa5c8744b81e0f64d5f9f709912613fbc8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
(define-module (Alpha String)
  #:export (replace replace-char to-string str capitalize))

(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 )))))


;;; {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)))))))))