Lisp - String Substring



Lisp provides subseq() method to get a substring from string.

Using subseq() method

The subseq function returns a sub-string (as a string is also a sequence) starting at a particular index and continuing to a particular ending index or the end of the string.

It is very useful method to extract a part of string as shown below.

Example - Substring till end of the string

Following code shows how to get a substring starting from a given index till the end of the string.

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

main.lisp

; print substring of statement starting from index 6
(write-line (subseq "Hello World" 6))

Output

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

World

Example - Substring from start index till end index

Following code shows how to get a substring starting from a given index till a given end index.

main.lisp

; print substring of statement starting from index 10 to 25
(write-line (subseq "Welcome to Tutorialspoint World" 10 25 ))

Output

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

Tutorialspoint

Example - Invalid Start Index

As string is an array of characters, subseq uses aref function to get the relevant indexes. If start index is invalid, LISP interpreter will complain as shown in code below:

main.lisp

; Error as start index is invalid
(write-line (subseq "Welcome to Tutorialspoint World" 40 ))

Output

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

*** - SUBSEQ: :START =40 should not be greater than :END = 31

Example - Invalid End Index

As string is an array of characters, subseq uses aref function to get the relevant indexes. If end index is invalid, LISP interpreter will complain as shown in code below:

main.lisp

; Error as end index is invalid
(write-line (subseq "Welcome to Tutorialspoint World" 20 50))

Output

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

*** - AREF: index 31 for "Welcome to Tutorialspoint World" is out of range
Advertisements