Question

I'm new to Clojure. I'm defining a vector containing string values. The requirement is to retrieve the String values separated by comma from the input vector. For example:

(def my-strings ["one" "two" "three"])

My expected output should be:

"one", "two", "three" 

I tried interpose and join as shown below:

(apply str (interpose "," my-strings))
(clojure.string/join "," my-strings)

Both returning "one,two,three" but I need each string surrounded by double quotes "" like in my example above.

Was it helpful?

Solution

Use map to surround each string with quotes, and notice how we represent a single quote using \", a character literal:

(clojure.string/join "," (map #(str \" % \") my-strings))
=> "one","two","three"

Be warned, though: a string is the text contained inside the "" characters, but the quotes themselves are not part of the string. so the "one,two,three" output is not wrong per se, unless you really really need those extra quotes surrounding the text.

OTHER TIPS

Your expected output in no way can be "one", "two", "three". What type would it be, then? Dynamic types are not no-types. But, of course, you can have it as string. And this string has to be represented somehow in repl.

Also please remember that comma , in Clojure is whitespace.

Special characters, like ", shall be escaped. In this case: \".

The quotes that you see in repl are not parts of the string (unless escaped). The string is one, not "one". If you want "one", you see "\"one\"".

The Answer of Óscar is not precise. The code does not output what is shown there. It outputs "\"one\",\"two\",\"three\"". (You may add one extra space after , to exactly match your requirement.).

Nevertheless, his answer is correct: It gives you exactly what you want. It is a string consisting of a word one surrounded by double quotes and followed by a comma, etc.

Try to spit it into a file. I did (adding extra space after comma). The file had:

"one", "two", "three"

Cheers -

P.S. LightTable is AWESOME !!!

The following also does the trick:

(let [strs ["one" "two" "three"]]
  (println
    ;;              outer quote       strings    outer quote
    (apply str (flatten [\" (interpose "\",\"" strs) \"]))))

Output:

user=> (let [strs ["one" "two" "three"]] (println (apply str (flatten [\" (interpose "\",\"" strs) \"]))))
"one","two","three"
nil
user=>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top