String split function
Asked Answered
R

3

10

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)
Reggie answered 7/10, 2011 at 19:6 Comment(2)
You should put your closing parens on the same line as the last expression. This isn't C :)Groupie
No, should do whatever you like.Internship
M
13

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")
Metasomatism answered 7/10, 2011 at 19:26 Comment(1)
Usually something like #px" +" or #px"[[:space:]]" is more appropriate. (In case that was the intention.)Subjectify
L
9

Well, you can use plain old string-split

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

It is part of racket http://docs.racket-lang.org/reference/strings.html#%28def._%28%28lib._racket%2Fstring..rkt%29._string-split%29%29

Lated answered 17/5, 2015 at 7:32 Comment(0)
G
7

Just as a reference for other Schemers, I did this in Chicken Scheme using the irregex egg:

(use irregex)

(define split-regex
  (irregex '(+ whitespace)))

(define (split-line line)
  (irregex-split split-regex line))

(split-line "19 2.14 + 4.5 2 4.3 / - *") =>
("19" "2.14" "+" "4.5" "2" "4.3" "/" "-" "*")
Groupie answered 10/10, 2011 at 2:32 Comment(1)
If you don't want to copy that definition every time, (string-split) is also a part of the coops egg, which has some other nice string stuff. Unfortunately it's not documented on its doc page.Carrizales

© 2022 - 2024 — McMap. All rights reserved.