In an instance were we want to replace a string with a different string, the replace
method comes in handy.
A string is a sequence of characters enclosed in double “ ”
quotation marks. One of the methods used to work with strings is the string replace
method.
replace
method in Clojure strings?The string replace
is a method used in Clojure to replace a matching string with another string.
(replace str match replacement)
The string replace
method accepts three (3) parameters:
str
: Represents the string containing the string to be replaced.match
: The string to be replaced.replacement
: The string replacing the match.This method returns the string with the part in match
replaced by the string in replacement
.
(ns clojure.examples.hello (:gen-class)) (defn example [] (println (clojure.string/replace "People work on themselves" #"themselves" "project"))) (example)
Line 3: We create a function called example
.
Line 4: Inside the example function
we use the replace
method to return the string.
Note: Notice how we call thereplace
method usingclojure.string/replace
. We use the dot notation on Clojure since thestring/replace
is the core Clojure method. We then replace the stringthemselves
withproject
because the string we want to replace has been inside of the main string.
Line 6: We simply call the example
function we created.
RELATED TAGS
CONTRIBUTOR
View all Courses