From d2901b5b8d91c9466fd37fc9d094fb6f0d4ea044 Mon Sep 17 00:00:00 2001 From: Arne Babenhauserheide Date: Fri, 11 Nov 2022 21:26:45 +0100 Subject: [PATCH] New function string-split-substring in (ice-9 string-fun) * module/ice-9/string-fun.scm (string-split-substring): as stated. * doc/ref/api-data.texi: Document the new function. * test-suite/tests/strings.test: Test. --- doc/ref/api-data.texi | 10 ++++++++++ module/ice-9/string-fun.scm | 29 ++++++++++++++++++++++++++++- test-suite/tests/strings.test | 5 ++++- 3 files changed, 42 insertions(+), 2 deletions(-) diff --git a/doc/ref/api-data.texi b/doc/ref/api-data.texi index 8658b9785..fe93b2030 100644 --- a/doc/ref/api-data.texi +++ b/doc/ref/api-data.texi @@ -4245,6 +4245,16 @@ Return a new string where every instance of @var{substring} in string @end lisp @end deffn +@deffn {Scheme Procedure} string-split-substring str substring +Return a new list of strings after splitting the string @var{str} +by @var{substring}. For example: + +@lisp +(string-split-substring "a ring of strings" "ring") +@result{} '("a " " of st" "s") +@end lisp +@end deffn + @node Representing Strings as Bytes @subsubsection Representing Strings as Bytes diff --git a/module/ice-9/string-fun.scm b/module/ice-9/string-fun.scm index 592b49e20..049dc2394 100644 --- a/module/ice-9/string-fun.scm +++ b/module/ice-9/string-fun.scm @@ -26,7 +26,7 @@ separate-fields-before-char string-prefix-predicate string-prefix=? sans-surrounding-whitespace sans-trailing-whitespace sans-leading-whitespace sans-final-newline has-trailing-newline? - string-replace-substring)) + string-replace-substring string-split-substring)) ;;;; ;;; @@ -313,3 +313,30 @@ (else (display (substring/shared str start))))))))) + + +;;; {String Fun: string-split-substring} +;;; + +;; string-split-substring By A. Babenhauserheide based on +;; string-replace-substring + +(define (string-split-substring str substring) + "Return a new list of strings after splitting the string @var{str} + by @var{substring}. For example: + + @lisp + (string-split-substring \"a ring of strings\" \"ring\") + @result{} '(\"a \" \" of st\" \"s\") + @end lisp + " + (if (equal? substring "") + (map string (string->list str)) ;; split each letter + (let ((sublen (string-length substring))) + (let lp ((start 0) (res '())) + (cond + ((string-contains str substring start) + => (lambda (end) + (lp (+ end sublen) (cons (substring/shared str start end) res)))) + (else + (reverse! (cons (substring/shared str start) res)))))))) diff --git a/test-suite/tests/strings.test b/test-suite/tests/strings.test index 7393bc8ec..c73451efc 100644 --- a/test-suite/tests/strings.test +++ b/test-suite/tests/strings.test @@ -699,4 +699,7 @@ (pass-if "string-replace-substring" (string=? (string-replace-substring "a ring of strings" "ring" "rut") - "a rut of struts"))) + "a rut of struts")) + (pass-if "string-split-substring" + (equal? (string-split-substring "a ring of strings" "ring") + '("a " " of st" "s")))) -- 2.38.0