Lisp - String Replacement



We can have multiple options to perform String replacement in Lisp. For character by character replacement, substitute() is a good choice.

substitute new-char old-char sequence

Where−

  • new-char− new char to be used

  • old-char− old char to be replaced

  • sequence− sequence or string where substitution is to be done.

Lisp strings are immutable, substitute method returns a new string after doing the substitution.

Example - Substituting space with .

Create a new source code file named main.lisp and type the following code in it.

main.lisp

; Replace space with .
(write-line(substitute #\. #\SPACE "When is the test")) 

Output

When you execute the code, it returns the following result −

When.is.the.test

Example - Substituting i with o

main.lisp

; Replace i with o
(write-line(substitute #\o #\i "When is the test")) 

Output

When you execute the code, it returns the following result −

When os the test

Example - Custom Substitution Method

We can write our own custom logic to replace strings using concatenate, subseq and search method as shown below:

main.lisp

(defun replace-str (string old-substr new-substr)
   (let ((start (search old-substr string)))
      (if start
         (concatenate 'string
            (subseq string 0 start)
             new-substr
            (subseq string (+ start (length old-substr))))
      string)))

(write-line (replace-str "A quick brown fox" "brown" "red"))

Output

When you execute the code, it returns the following result −

A quick red fox
Advertisements