Splitting a string in Racket
Asked Answered
I

1

7

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.

Interpenetrate answered 26/9, 2017 at 20:19 Comment(1)
You could use (map string (string->list str)).Apocalyptic
C
8

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"))
Casaubon answered 26/9, 2017 at 20:56 Comment(2)
howto split expression into sub expressions?Override
Why does the default behavior with an empty-string separator produce the empty strings in the output?Drink

© 2022 - 2024 — McMap. All rights reserved.