Lisp - Sorting Strings



Lisp provides sort() method to sort strings. sort() method takes sequence which can be a list of strings or a vector of strings to be sorted and a comparison function. In this chapter, we'll explore multiple ways to sort strings using sort() method

Example - case insensitive sorting of strings

We can use string-lessp as a case insensitive comparison function to sort strings.

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

main.lisp

; case insensitive sorting of list of strings
(write (sort '("banana" "apple" "orange") #'string-lessp))

Output

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

("apple" "banana" "orange")

We can use vector of strings as input to sort as well as shown below:

main.lisp

; case insensitive sorting of vectors of strings
(write (sort (vector "banana" "apple" "orange") #'string-lessp))

Output

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

("apple" "banana" "orange")

Example - case sensitive sorting of strings

We can use string< as a case sensitive comparison function to sort strings.

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

main.lisp

; case sensitive sorting of list of strings
(write (sort '("apple" "APPLE" "orange") #'string<))
; terminate printing
(terpri)
; case in-sensitive sorting of list of strings
(write (sort '("apple" "APPLE" "orange") #'string-lessp))

Output

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

("APPLE" "apple" "orange")
("apple" "APPLE" "orange")

We can use vector of strings as input to sort as well as shown below:

main.lisp

; case sensitive sorting of vector of strings
(write (sort (vector "apple" "APPLE" "orange") #'string<))
; terminate printing
(terpri)
; case in-sensitive sorting of vector of strings
(write (sort (vector "apple" "APPLE" "orange") #'string-lessp))

Output

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

("APPLE" "apple" "orange")
("apple" "APPLE" "orange")
Advertisements