Lisp - String Searching



Lisp provides search() method to search a string within a string.

Using search() method

search() is a very flexible method to perform a string search as well as search on sequences. We can customize search() method using :test keyword along with #'string-equal to do a case-insensitive search.

Example - case sensitive search for available text

search() method returns the index of string found otherwise NIL is returned.

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

main.lisp

; search a string, return 3 
(write (search "point" "tutorialspoint.com"))
; terminate printing
(terpri)
; search is case sensitive
(write (search "Point" "tutorialspoint.com"))

Output

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

9
NIL

Example - case insensitive search for available text

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

main.lisp

; case in-sensitive
(write (search "Point" "tutorialspoint.com" :test #'string-equal))

Output

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

9

Example - case sensitive search for non-available text

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

main.lisp

; search a string, return NIL
(write (search "abc" "tutorialspoint.com"))

Output

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

NIL

Example - case insensitive search for non-available text

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

main.lisp

; case in-sensitive
(write (search "abc" "tutorialspoint.com" :test #'string-equal))

Output

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

NIL
Advertisements