How to use the replace method in Clojure strings
Overview
In an instance were we want to replace a string with a different string, the replace method comes in handy.
What are strings in Clojure?
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.
What is the string replace method in Clojure strings?
The string replace is a method used in Clojure to replace a matching string with another string.
Syntax
(replace str match replacement)
Parameter
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.
Return value
This method returns the string with the part in match replaced by the string in replacement.
Example
(ns clojure.examples.hello(:gen-class))(defn example [](println (clojure.string/replace "People work on themselves" #"themselves""project")))(example)
Explanation
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 thereplacemethod usingclojure.string/replace. We use the dot notation on Clojure since thestring/replaceis the core Clojure method. We then replace the stringthemselveswithprojectbecause the string we want to replace has been inside of the main string.
Line 6: We simply call the example function we created.