The string is probably the most frequently-used data structure in all languages. However, the idea and implementation of a string varies from language to language.

In Clojure, strings are text between a pair of "(double quote) characters. The '(single quote) isn’t used to express strings in Clojure. When we want to use double quotes within a string, they must be escaped by \(backslash).

user> (def kind "a rose")
user> kind
"a rose"
user> (println kind)
a rose
user> (def name "that rose has a name \"The ROSE\"")
user> name
"that rose has a name \"The ROSE\""
user> (println name)
that rose has a name "The ROSE"

user> ; if we use a single quote...
user> (def bad-kind 'a rose')
CompilerException java.lang.RuntimeException: Too many arguments to def, compiling:(/private/var\
user> ; a single quote is a syntax quote, so Clojure sees there are 'a and rose' in def.

Clojure strings have the type java.lang.String. This means Clojure strings can use all methods defined for java.lang.String. See the Java API document:

  • Advice to coaches

    This document doesn’t have a section for Java interoperability. Please talk about Java method invocation on Clojure briefly.

user> (type "rose")

user> (.startsWith "rose" "r")  ; startsWith Java method
user> (.replace "rose" "r" "R")  ; replace Java method
user> (.compareTo "rose" "roses")
user> (+ "lovely " "rose")  ; Clojure's + function doesn't work
ClassCastException java.lang.String cannot be cast to java.lang.Number  clojure.lang.Numbers.add\
user> (.concat "lovely " "rose")  ; concat Java method works
"lovely rose"

user> (.length "rose")

In addition to the methods of java.lang.String, Clojure functions also work for strings.

  • Advice to coaches

    Links to string-related functions are listed in References. Tell attendees to try some other functions by looking at documents.

user> (compare "rose" "roses") ; the same as java.lang.String's compareTo method
user> (str "lovely " "rose")  ; the same as java.lang.String's concat method
"lovely rose"
user> (count "rose") ; the same as java.lang.String's length method

user> ;; many of string related functions are defined in clojure.string namespace

user> (clojure.string/reverse "rose")
user> (clojure.string/replace-first "rose" #"r" "R")
user> (clojure.string/capitalize "rose")
user> (clojure.string/upper-case "rose")

In Clojure, strings are seq-able. Clojure functions for seq also work for strings. When those functions are used on strings, Character type values are returned.

Characters have the java.lang.Character type and are expressed as \ followed by a single letter.

user> (take-nth 2 "rose")
(\r \s)
user> (rest "rose")
(\o \s \e)
user> (clojure.string/join (rest "rose"))