2011-10-07 12 views
10

Zastanawiam się tylko, czy istnieje funkcja podziału struny? Coś jak:Funkcja podziału struny

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

Nie znalazłem go i stworzył własne. Używam Schematu od czasu do czasu, więc będę wdzięczny, jeśli go naprawisz i zaproponujesz lepsze rozwiązanie:

#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

powinien umieścić swoje nawiasów zamykających na tej samej linii co ostatniej wypowiedzi. To nie jest C :) – erjiang

+2

Nie, powinieneś robić, co chcesz. – rightfold

Odpowiedz

13

O mój! To dużo pracy. Jeśli rozumiem Twojego problemu poprawnie, użyłbym regexp-split na to:

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

=>

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

Zwykle bardziej odpowiednie jest coś w rodzaju '#px" + "' lub '#px" [[: space:]] "'. (Jeśli taka była intencja). –

6

tylko jako punkt odniesienia dla innych intrygantów, zrobiłem to na schemacie Chicken pomocą irregex jajo :

(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

Jeśli nie chcesz kopiować tej definicji za każdym razem, '' (string-split) 'jest również częścią jaja' coops', które ma kilka innych fajnych stringów. Niestety nie jest to udokumentowane na stronie dokumentu. – user1610406