One of the most common programming tasks is transformation and manipulation of strings. Regular expressions are also an essential tool to process strings and is included in this section.
str
is one of the most used Clojure functions. It takes one or more strings and returns their concatenation:
(str "Should " "this " "be " "a " "single " "sentence?") ; #1 ;; "Should this be a single sentence?"
But str
is not limited to strings, because it converts any non-string before concatenating it. It is common to see str
used on all sort of values, because every type in Clojure (inheriting this behavior from Java) contains at least a default conversion to string. Sometimes this behavior is not desirable, as in the case of lazy sequences:
(str :a 'b 1e8 (Object.) [1 2] {:a 1}) ; #1 ;; ":ab1.0E8java.lang.Object@dd2856e[1 2]{:a 1}" (str (map inc (range 10))) ; #2 ;; "clojure.lang.LazySeq@c5d38b66" (pr-str (map inc (range 10))) ; #3 ;; "(1 2 3 4 5 6 7 8 9 10)"
Another typical use of str
is on collections with either apply or reduce. The resulting string is equivalent to the concatenation of all the items in the input collection:
(apply str (range 10)) ; #1 ;; "0123456789" (reduce str (interpose "," (range 10))) ; #2 ;; "0,1,2,3,4,5,6,7,8,9"