Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

community creator
clojure

How to use the replace method in Clojure strings

Chinweuba Elijah Azubuike

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:

  1. str: Represents the string containing the string to be replaced.
  2. match: The string to be replaced.
  3. 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)
Replace method in Clojure

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 the replace method using clojure.string/replace. We use the dot notation on Clojure since the string/replace is the core Clojure method. We then replace the string themselves with project 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

community creator
clojure

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring