字符串拆分功能

时间:2011-10-07 19:06:46

标签: scheme racket

我只是想知道是否有字符串拆分功能?类似的东西:

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

我没有找到它并创建了我自己的。我会不时使用Scheme,所以如果你修复它并提出更好的解决方案,我将感激不尽:

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

3 个答案:

答案 0 :(得分:13)

哦,我的!这是很多工作。如果我理解你的问题,我会使用regexp-split:

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

=>

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

答案 1 :(得分:7)

作为其他Schemers的参考,我使用irregex鸡蛋在Chicken Scheme中做了这个:

(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" "/" "-" "*")

答案 2 :(得分:5)

好吧,您可以使用普通的旧字符串拆分

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

这是球拍http://docs.racket-lang.org/reference/strings.html#%28def._%28%28lib._racket%2Fstring..rkt%29._string-split%29%29

的一部分