Splitting a string in Racket

Viewed 5600

I want to convert a string into a list of one strings in Racket:

(string-split-wishful "abcd" "") => (list "a" "b" "c" "d")

This is the function that I wish for. The closest thing is string-split which doesn't do what I want:

(string-split "abcd" "") => (list "" "a" "b" "c" "d" "")

How do I get rid of the superfluous empty strings at the beginning and the end? I know that I can do something like (reverse (cdr (reverse (cdr (string-split "abcd" ""))))) but I want to know if there's a more idiomatic way of doing this.

1 Answers

Try this:

(string-split "abcd" #rx"(?<=.)(?=.)")
; ==> ("a" "b" "c" "d")

It uses a regular expression instead of string and the regular expression consist of a zero-width positive look-behind assertion such that it only matches after a character and one zero-width positive look-ahead assertion such that the match need one char in its right side to match.

Alexis' suggestion is nice too, might even perform better too:

(map string (string->list "abcd"))
Related