Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split string at fixed numbers of character in clojure?

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.

like image 255
rishi kant Avatar asked Jul 28 '16 10:07

rishi kant


People also ask

How do you split a string at a certain character?

To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.

How do I split a string into substrings?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do I split multiple strings?

String split() Method: The str. split() function is used to split the given string into array of strings by separating it into substrings using a specified separator provided in the argument.


2 Answers

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")
like image 65
leetwinski Avatar answered Oct 02 '22 08:10

leetwinski


(->> "hello everyone welcome to here"
     (partition-all 4)
     (map (partial apply str)))
like image 24
OlegTheCat Avatar answered Oct 02 '22 07:10

OlegTheCat