Clojure:
Concatenating strings
How to:
Clojure makes string concatenation straightforward with the str
function. Let’s dive right in:
;; Simple concatenation with the str function
(str "Hello, " "world!")
;; => "Hello, world!"
;; Concatenating multiple strings
(str "Clojure" " is" " awesome!")
;; => "Clojure is awesome!"
;; Combining strings and other values
(str "The answer is " 42)
;; => "The answer is 42"
;; Using apply to concatenate a sequence of strings
(apply str ["Join" " " "these" " " "strings!"])
;; => "Join these strings!"
Great, so you’ve seen it in action. Just remember str
works with any value by calling toString
on it. If it’s nil, you get the string “nil”.
Deep Dive
Historically, string concatenation has been around since we needed to handle text programmatically, and each language offers its own methods. In Clojure, str
is part of the core library, introduced for simplicity and uniformity.
Alternatives to str
? Yes! StringBuilder
can be more efficient for lots of concatenations, especially in loops. Clojure can call Java methods, so you can use StringBuilder
as well:
;; Using StringBuilder for efficiency
(let [builder (StringBuilder.)]
(.append builder "This is")
(.append builder " a more")
(.append builder " efficient way!")
(.toString builder))
;; => "This is a more efficient way!"
Why not always use StringBuilder
then? For most everyday tasks, str
is simpler and fast enough. StringBuilder
shines in high-performance scenarios with many concatenations.
Implementation-wise, since Clojure is hosted on the JVM, it benefits from Java’s string handling capabilities. However, like in Java String
s, each str
call creates a new String
, which can be a memory consideration.
See Also
- Clojure’s
str
function documentation: Clojure Strings - Java’s
StringBuilder
: StringBuilder Docs - Practical Clojure guide to
str
and more: Clojure for the Brave and True