String split function

demas picture demas · Oct 7, 2011 · Viewed 9.8k times · Source

I am just wondering if there is the string split function? Something like:

> (string-split "19 2.14 + 4.5 2 4.3 / - *")
'("19" "2.14" "+" "4.5" "2" "4.3" "/" "-" "*")

I haven't found it and created my own. I use Scheme from time to time so I'll be thankful if you fix it and suggest the better solution:

#lang racket

(define expression "19 2.14 + 4.5 2 4.3 / - *")

(define (string-split str)

  (define (char->string c)
    (make-string 1 c))

  (define (string-first-char str)
    (string-ref str 0))

  (define (string-first str)
    (char->string (string-ref str 0)))

  (define (string-rest str)
    (substring str 1 (string-length str)))

  (define (string-split-helper str chunk lst)
  (cond 
    [(string=? str "") (reverse (cons chunk lst))]
    [else
     (cond
       [(char=? (string-first-char str) #\space) (string-split-helper (string-rest str) "" (cons chunk lst))]
       [else
        (string-split-helper (string-rest str) (string-append chunk (string-first str)) lst)]
       )
     ]
    )
  )

  (string-split-helper str "" empty)
  )

(string-split expression)

Answer

John Clements picture John Clements · Oct 7, 2011

Oh my! That's a lot of work. If I understand your problem correctly, I would use regexp-split for this:

#lang racket
(regexp-split #px" " "bc thtn odnth")

=>

Language: racket; memory limit: 256 MB.
'("bc" "thtn" "odnth")