2011-10-07 14 views
10

¿Me pregunto si existe la función de división de cadenas? Algo como:Función de división de cadenas

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

No lo he encontrado y he creado el mío. Yo uso Esquema de vez en cuando así que estaré agradecido si usted fija y sugerir la mejor solución:

#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

Usted debe poner sus parens de cierre en la misma línea que la última expresión. Esto no es C :) – erjiang

+2

No, debería hacer lo que quiera. – rightfold

Respuesta

13

Oh! Eso es mucho trabajo. Si entiendo su problema correctamente, me gustaría utilizar expresiones regulares-split para esto:

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

=>

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

Por lo general, algo como '#px" + "' o '#px" [[: space:]] "' es más apropiado. (En caso de que fuera la intención). –

6

Sólo como referencia para otros conspiradores, hice esto en pollo Esquema usando el huevo irregex :

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

Si no quiere copiar esa definición cada vez, '(string-split)' también es parte del huevo 'coops', que tiene otras cosas agradables. Desafortunadamente no está documentado en su página de documentación. – user1610406

Cuestiones relacionadas