String Functions in Clojure

The standard library’s clojure.string namespace provides many useful string-related functions. Here are some examples to give you a sense of the namespace.

(ns string-functions
  (:require [clojure.string :as s]))

(defn main []
  (println "Contains:  " (s/includes? "test" "es"))
  (println "Count:     " (count (filter #(= % \t) "test")))
  (println "HasPrefix: " (s/starts-with? "test" "te"))
  (println "HasSuffix: " (s/ends-with? "test" "st"))
  (println "Index:     " (s/index-of "test" "e"))
  (println "Join:      " (s/join "-" ["a" "b"]))
  (println "Repeat:    " (s/repeat 5 "a"))
  (println "Replace:   " (s/replace "foo" "o" "0"))
  (println "Replace:   " (s/replace-first "foo" "o" "0"))
  (println "Split:     " (s/split "a-b-c-d-e" #"-"))
  (println "ToLower:   " (s/lower-case "TEST"))
  (println "ToUpper:   " (s/upper-case "test")))

(main)

Here’s a sample of the functions available in clojure.string. Since these are functions from the namespace, not methods on the string object itself, we need to pass the string in question as an argument to the function. You can find more functions in the clojure.string namespace docs.

To run the program, you can save it as string_functions.clj and use the Clojure CLI or REPL:

$ clj string_functions.clj
Contains:   true
Count:      2
HasPrefix:  true
HasSuffix:  true
Index:      1
Join:       a-b
Repeat:     aaaaa
Replace:    f00
Replace:    f0o
Split:      [a b c d e]
ToLower:    test
ToUpper:    TEST

Note that Clojure’s approach to string manipulation is slightly different from some other languages:

  1. Clojure uses includes? instead of Contains.
  2. For Count, we use a combination of filter and count as there’s no direct “count occurrences” function.
  3. Replace in Clojure replaces all occurrences by default, so we don’t need to specify -1 for “replace all”.
  4. For replacing only the first occurrence, we use replace-first.

These functions demonstrate Clojure’s functional approach to string manipulation, which can be very powerful and expressive once you’re familiar with it.