7

I'm new in clojure. I'm learning about splitting string in various ways. I'm taking help from here: https://clojuredocs.org/clojure.string/split There is no example to split string at fixed number of character.

Let a string "hello everyone welcome to here". I want to split this string after every 4th char, so the output (after split) should be ["hell" "o ev" "eryo" "ne w" "elco" "me t" "o he" "re"]. Note that white space is consider a char.

can anyone tell me, how can I do this? Thanks.

3 Answers 3

14

you could use re-seq:

user> (def s "hello everyone welcome to here")
#'user/s

user> (re-seq #".{1,4}" s)
("hell" "o ev" "eryo" "ne w" "elco" "me t" "o he" "re")

or partition the string, treating it as a seq:

user> (map (partial apply str) (partition-all 4 s))
("hell" "o ev" "eryo" "ne w" "elco" "me t" "o he" "re")
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. It's awesome. It solve my problem. @leetwinski
It would be cleaner to (require '[clojure.string :as str]) and use str/join instead of (partial apply str).
probably. Still re-seq approach is much faster (well, if you realize the seq)
5

With transducers:

(def sample "hello everyone welcome to here")

(into [] (comp (partition-all 4) (map #(apply str %))) sample)

Slower than the other examples though :).

1 Comment

(eduction (partition-all 4) (map #(apply str %)) sample) to be pretentious :)
4
(->> "hello everyone welcome to here"
     (partition-all 4)
     (map (partial apply str)))

1 Comment

Thanks. I got my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.