summaryrefslogtreecommitdiff
path: root/bs/string.scm
blob: 6d6e941615af9a2c1434f185f203193e1c637849 (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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!r6rs
(library (bs string (0))
  (export
   replace replace-char to-string str capitalize split
   strip lstrip rstrip prefix? suffix?)
  (import
    (rnrs base)
    (only  (rnrs control) case-lambda)
    (only (rnrs io simple) display)
    (only (srfi srfi-13)
          string-trim string-trim-both string-trim-right
          string-prefix? string-suffix? string-upcase string-concatenate
          string-drop string-take string-contains substring/shared string-null? string-fold)
    (only (srfi srfi-14) string->char-set)
    (only (srfi srfi-28) format)
    ;; TODO: remove or port ice-9 dependency
    (only (ice-9 ports) with-output-to-string))

  ;; Is `pre` a prefix of `s`?
  (define (prefix? s sub)
    (string-prefix? sub s))

  ;; Is `suf` a suffix of `s`?
  (define (suffix? s suf)
    (string-suffix? suf s))

  ;; Split `s` at `sep`
  (define (split s sep)
    (string-tokenize s (char-set-complement (apply char-set (string->list sep)))))

  ;; Replace `match` in `s` with `char`
  (define (replace-char s match char)
    (let ((f (lambda (a b)
               (let ((next-char (if (eq? a match) char a)))
                 (string-concatenate (list b (string next-char)))))))
      (string-fold f "" s)))

  ;; Replace `match` in `s` with `repl`
  (define (replace s match repl)
    ;; based on 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.
    (let ((matchlen (string-length match)))
      (with-output-to-string
        (lambda ()
          (let lp ((start 0))
            (cond
             ((string-contains s match start)
              => (lambda (end)
                   (display (substring/shared s start end))
                   (display repl)
                   (lp (+ end matchlen))))
             (else
              (display (substring/shared s start)))))))))

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