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.
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:
Note that Clojure’s approach to string manipulation is slightly different from some other languages:
- Clojure uses
includes?
instead ofContains
. - For
Count
, we use a combination offilter
andcount
as there’s no direct “count occurrences” function. Replace
in Clojure replaces all occurrences by default, so we don’t need to specify-1
for “replace all”.- 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.