字符串拆分功能

dem*_*mas 10 scheme racket

我只是想知道是否有字符串拆分功能?就像是:

> (string-split "19 2.14 + 4.5 2 4.3 / - *")
'("19" "2.14" "+" "4.5" "2" "4.3" "/" "-" "*")
Run Code Online (Sandbox Code Playgroud)

我没有找到它并创建了我自己的.我不时使用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)
Run Code Online (Sandbox Code Playgroud)

Joh*_*nts 13

天啊!这是很多工作.如果我正确理解你的问题,我会使用regexp-split为此:

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

=>

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

  • 通常像`#px"+"`或`#px"[[:space:]]"`更合适.(如果是意图.) (3认同)

erj*_*ang 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" "/" "-" "*")
Run Code Online (Sandbox Code Playgroud)


Lux*_*pes 5

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

> (string-split "19 2.14 + 4.5 2 4.3 / - *")
'("19" "2.14" "+" "4.5" "2" "4.3" "/" "-" "*")
Run Code Online (Sandbox Code Playgroud)

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