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=> 
Share:
11,382

Related videos on Youtube

Adam Sznajder
Author by

Adam Sznajder

Coding means fun! Personal blog: asznajder.github.com

Updated on September 14, 2022

Comments

  • Adam Sznajder
    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
    Adam Sznajder almost 12 years
    Is there any way to do this using map?
  • Sergey
    Sergey almost 12 years
    You can use reduce here: (reduce str ["a" "b" "c"]) but I'd better use join function.
  • NielsK
    NielsK almost 12 years
    If you don't need the separator of clojure.string/join, apply str is the better solution.
  • Andrew Whitehouse
    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
    M Smith almost 12 years
    If you do want delimited you can use interpose thusly (apply str (interpose "," ["a" "b" "c"])) => "a,b,c"
  • sheldonh
    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
    NielsK over 8 years
    1 - 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 in str.
  • NielsK
    NielsK over 8 years
    If you only want to use delimiters for use in the final string, better use clojure.string/join, instead of apply str combined with interpose. 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
    NielsK over 8 years
    While 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.