Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: Insert spaces into string every x chars

Tags:

string

clojure

I have a long clojure String, and I need to split it with spaces every 2 characters (ex: "1234567890" --> "12 34 56 78 90". The solution I used is:

(->>
  (partition 2 2 "" s)
  (map (partial join ""))
  (join " "))

Is there any simpler way to do this?

like image 963
Asher Avatar asked Dec 13 '25 03:12

Asher


2 Answers

You can do it with regex, but is this simpler? For me - yes, but it looks like a matter of taste.

user> (clojure.string/replace "1234567890" #"(.{2})(?!$)" "$1 ")
"12 34 56 78 90"
like image 75
coredump Avatar answered Dec 16 '25 10:12

coredump


Another possible variant:

user=> (->> "1234567890" (partition 2) (map #(apply str %))
            (clojure.string/join " "))
"12 34 56 78 90"
like image 41
edbond Avatar answered Dec 16 '25 10:12

edbond



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!