Lisp - String Comparison



Numeric comparison functions and operators, like, < and > do not work on strings. Common LISP provides other two sets of functions for comparing strings in your code. One set is case-sensitive and the other case-insensitive.

The following table provides the functions −

Case Sensitive Functions Case-insensitive Functions Description
string= string-equal Checks if the values of the operands are all equal or not, if yes then condition becomes true.
string/= string-not-equal Checks if the values of the operands are all different or not, if values are not equal then condition becomes true.
string< string-lessp Checks if the values of the operands are monotonically decreasing.
string> string-greaterp Checks if the values of the operands are monotonically increasing.
string<= string-not-greaterp Checks if the value of any left operand is greater than or equal to the value of next right operand, if yes then condition becomes true.
string>= string-not-lessp Checks if the value of any left operand is less than or equal to the value of its right operand, if yes then condition becomes true.

Example - Using Case Sensitive functions

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

main.lisp

; case-sensitive comparison for equality
(write (string= "this is test" "This is test"))
; terminate printing
(terpri)
; case-sensitive comparison for greater than
(write (string> "this is test" "This is test"))
; terminate printing
(terpri)
; case-sensitive comparison for less than
(write (string< "this is test" "This is test"))
; terminate printing
(terpri)

Output

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

NIL
0
NIL

Example - Using Case In-sensitive functions

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

main.lisp

; case-sensitive comparison for equality
(write (string= "this is test" "This is test"))
; terminate printing
(terpri)
; case-sensitive comparison for greater than
(write (string> "this is test" "This is test"))
; terminate printing
(terpri)
; case-sensitive comparison for less than
(write (string< "this is test" "This is test"))
; terminate printing
(terpri)

Output

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

T
NIL
NIL

Using Start/End Indices

We can use start and end indices as well while comparing strings.

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

main.lisp

(write(string= "hello world" "hello" :end1 5))

Output

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

T
Advertisements