Concatenation of the strings vector in Clojure
11,382
Solution 1
You can use clojure.string join function for that
(clojure.string/join ["a" "b" "c"])
Solution 2
You can use apply
with the str
function:
(apply str ["a" "b" "c"])
Solution 3
This is one of the ways Clojure's reduce can be used. Note the session at Clojure's REPL:
[dsm@localhost:~]$ clj
Clojure 1.4.0
user=> (reduce str ["a" "b" "c"])
"abc"
user=>
Related videos on Youtube
Author by
Adam Sznajder
Coding means fun! Personal blog: asznajder.github.com
Updated on September 14, 2022Comments
-
Adam Sznajder over 1 year
I would like to concatenate strings stored in a vector. For example if I have
["a" "b" "c"]
in the vector I would like to get as a result"abc"
. -
Adam Sznajder almost 12 yearsIs there any way to do this using
map
? -
Sergey almost 12 yearsYou can use reduce here: (reduce str ["a" "b" "c"]) but I'd better use join function.
-
NielsK almost 12 yearsIf you don't need the separator of clojure.string/join, apply str is the better solution.
-
Andrew Whitehouse almost 12 years(apply str <sequence>) is the approach you will see used most often (as NielsK says, as long as you don't need the separator)
-
M Smith almost 12 yearsIf you do want delimited you can use
interpose
thusly(apply str (interpose "," ["a" "b" "c"])) => "a,b,c"
-
sheldonh over 8 years@NielsK Why is
str
a better solution when no separator is required? I arrived here looking for the answer to that question. :-) -
NielsK over 8 years1 - str is in core, so no need for extra namespaces to be loaded. 2 - In
join
without seperator there's a superfluous call for (.append sb "") per item in coll, which isn't done instr
. -
NielsK over 8 yearsIf you only want to use delimiters for use in the final string, better use
clojure.string/join
, instead ofapply str
combined withinterpose
. The latter uses a lot more allocations. If you want to alter the collection some more before turning it into a string,interpose
is the way to go though. -
NielsK over 8 yearsWhile this may seem trivial, there's large performance gains to be had. Instead of calling
str
left and right during construction of very large strings, building a large collection and calling(apply str coll)
(or even(apply str (flatten coll))
) only once makes a huge difference.