【发布时间】:2011-12-03 06:07:10
【问题描述】:
我只是想知道是否有字符串拆分功能?比如:
> (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)
【问题讨论】:
-
你应该把你的右括号放在最后一个表达式的同一行。这不是 C :)
-
不,应该为所欲为。