Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String split function

Tags:

scheme

racket

I am just wondering if there is the string split function? Something like:

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

I haven't found it and created my own. I use Scheme from time to time so I'll be thankful if you fix it and suggest the better solution:

#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)
like image 534
ceth Avatar asked Oct 07 '11 19:10

ceth


People also ask

What does split \\ do in Java?

split() The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings.


2 Answers

Well, you can use plain old string-split

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

It is part of racket http://docs.racket-lang.org/reference/strings.html#%28def._%28%28lib._racket%2Fstring..rkt%29._string-split%29%29

like image 106
Luxspes Avatar answered Sep 28 '22 22:09

Luxspes


Just as a reference for other Schemers, I did this in Chicken Scheme using the irregex egg:

(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" "/" "-" "*")
like image 21
erjiang Avatar answered Sep 28 '22 23:09

erjiang