Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add character to string to get another string?

Tags:

I want to add a character to a string, and get another string with the character added as a result.

This doesn't work:

(cons \a "abc") 

Possible solutions, in order of preference:

  1. Clojure core function
  2. Clojure library function
  3. Clojure user-defined (me!) function (such as (apply str (cons \a "abc")))
  4. java.lang.String methods

Is there any category 1 solution before I roll-my-own?


Edit: this was a pretty dumb question. :(

like image 790
Matt Fenwick Avatar asked Nov 10 '11 16:11

Matt Fenwick


2 Answers

How about:

(str "abc" \a) 

This returns "abca" on my machine.

You can also use it for any number of strings/chars: (str "kl" \m "abc" \a \b).

like image 187
Dan Filimon Avatar answered Sep 27 '22 22:09

Dan Filimon


You could use join from clojure.string:

(clojure.string/join [\a "abc"])

But for the simple use case you should really just use str, as @Dan Filimon suggests. join has the added benefit that you could put a separator between the joined strings, but without a separator it actually just applies str:

(defn ^String join   "Returns a string of all elements in coll, separated by    an optional separator.  Like Perl's join."   {:added "1.2"}   ([coll]      (apply str coll))   ([separator [x & more]]      (loop [sb (StringBuilder. (str x))             more more             sep (str separator)]        (if more          (recur (-> sb (.append sep) (.append (str (first more))))                 (next more)                 sep)          (str sb))))) 
like image 41
Christian Berg Avatar answered Sep 27 '22 20:09

Christian Berg