t3x.org / nss / string-split.html

(Nils' Scheme Snippets)

 
Paren matching: ON  |  Category: strings  |  Overview  |  Scheme Books  |  License
 

(string-split char string) => list

 
Purpose
Split a string into substrings. Return a list containing all cohesive sequences of non-delimiting characters contained in the given string.
 
Arguments
c delimiting character
s string to split
 
Example
(string-split #\space  " to be  or  not to be ")
=> ("to" "be" "or" "not" "to" "be")
(define (string-split c s)
  (letrec
    ((skip-delimiters
       (lambda (i k)
         (cond
           ((= i k) i)
           ((char=? (string-ref s i) c)
             (skip-delimiters (+ i 1) k))
           (else i))))
     (split (lambda (i k tmp res)
       (cond
         ((= i k)
           (if (string=? "" tmp)
               res
               (cons tmp res)))
         ((char=? (string-ref s i) c)
           (split (skip-delimiters i k) k "" (cons tmp res)))
         (else (split (+ i 1) k
                 (string-append tmp
                   (string (string-ref s i)))
                 res))))))
    (let ((k (string-length s)))
      (reverse (split (skip-delimiters 0 k) k "" '())))))

Copyright (C) 2007 Nils M Holm <nmh @ t3x . org>