Lisp - String Trimming



Lisp provides various methods for string trimming.

String trimming methods

The following table describes the string trimming functions −

Sr.No. Function & Description
1

string-trim

It takes a string of character(s) as first argument and a string as the second argument and returns a substring where all characters that are in the first argument are removed off the argument string.

2

String-left-trim

It takes a string of character(s) as first argument and a string as the second argument and returns a substring where all characters that are in the first argument are removed off the beginning of the argument string.

3

String-right-trim

It takes a string character(s) as first argument and a string as the second argument and returns a substring where all characters that are in the first argument are removed off the end of the argument string.

Example - Using Built-in Trimming Functions

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

main.lisp

; trim and print the statement
(write-line (string-trim " " "   a big hello from tutorials point   "))
; trim spaces on left and print the statement
(write-line (string-left-trim " " "   a big hello from tutorials point   "))
; trim spaces on right and print the statement
(write-line (string-right-trim " " "   a big hello from tutorials point   "))
; trim spaces on both left and right and print the statement
(write-line (string-trim " a" "   a big hello from tutorials point   "))

Output

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

a big hello from tutorials point
a big hello from tutorials point   
   a big hello from tutorials point
big hello from tutorials point

Example - Using Custom Trimming Functions

We can define our own custom trim function as well to trim given character as shown below. Update main.lisp code as shown below−

main.lisp

(defun trim (string chars)
  (let ((start (position-if-not (lambda (c) (find c chars)) string))
        (end (position-if-not (lambda (c) (find c chars)) string :from-end t)))
    (if (and start end)
        (subseq string start (1+ end))
        (if start
            (subseq string start)
            (if end
                (subseq string 0 (1+ end))
                "")))))
				
(print (trim "xxHello, world!xx" #(#\x)))
(print (trim "**Welcome to Tutorialspoint**" #(#\*)))    

Output

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

Hello, world!
Welcome to Tutorialspoint
Advertisements