Skip to content
AgileLogics
6 min read

Strings and Characters

Prerequisites: Numbers and math

Clojure strings are Java strings, written in double quotes.

(def person "Ada")

(println (str "Hello, " person "!"))
(println (str "Next year: " (+ 36 1)))
(println (format "%s is %d years old" person 36))
(println (count person))
(println (subs "Clojure" 0 3))
(println (subs "Clojure" 3))
(println "Line one\nLine two\tTabbed \"quoted\"")
Hello, Ada!
Next year: 37
Ada is 36 years old
3
Clo
jure
Line one
Line two	Tabbed "quoted"
  • str concatenates anything into a string (nil becomes "").
  • format works like Java's String.format.
  • subs takes a start index and an optional end (exclusive).
  • Escapes: \n, \t, \", \\.

clojure.string

The clojure.string namespace has the everyday string functions. Load it with require and give it a short alias:

(require '[clojure.string :as str])

(println (str/upper-case "clojure"))
(println (str/capitalize "hello world"))
(println (str/trim "   padded   "))
(println (str/split "red,green,blue" #","))
(println (str/join ", " ["a" "b" "c"]))
(println (str/replace "a-b-c" "-" "+"))
(println (str/includes? "clojure" "jure"))
(println (str/starts-with? "clojure" "clo"))
(println (str/blank? "   "))
(println (str/reverse "stressed"))
CLOJURE
Hello world
padded
[red green blue]
a, b, c
a+b+c
true
true
true
desserts

#"," is a regular expression literal (more in Level 2). The alias str doesn't clash with the str function: str/join means "join from the namespace aliased as str".

Characters

(println \a (int \a) (char 66))
(println (seq "hey"))
(println (apply str (reverse "hello")))
(println (Character/isDigit \7))
(println (map int "AB"))
a 97 B
(h e y)
olleh
true
(65 66)

A character literal is written \a (\space, \newline for special ones). A string can be treated as a sequence of characters — seq, reverse, map, and every other sequence function work on it.

Practice

Given " the quick brown fox ", print it trimmed with each word capitalized, joined by single spaces.

Show solution
(require '[clojure.string :as str])

(def text "  the quick brown fox  ")
(println (str/join " " (map str/capitalize (str/split (str/trim text) #"\s+"))))
The Quick Brown Fox