Skip to content

LISP - String length

In Common Lisp, length is a generic function used to find the number of elements in any sequence. Since strings are a type of sequence (specifically, a vector of characters), length is the standard function to determine a string’s length.

The usage is straightforward: pass the sequence as an argument to the length function.

Let’s define a string and use the length function to get the count of its characters.

;; Define a string using a local variable
(let ((my-string "Modern Lisp is powerful!"))
;; Get its length
(length my-string))
24

A common mistake for beginners is to quote a string literal, like (length '"my-string"). This is incorrect. The single quote (') is shorthand for the quote special operator, which prevents evaluation.

  • "my-string": This is a string literal. It evaluates to itself, a string object containing characters.
  • '"my-string": This is a symbol. It evaluates to the symbol whose name is my-string. A symbol is not a string, and trying to get its length will result in an error.
;; CORRECT: Get the length of a string
(length "Hello") ; => 5
;; INCORRECT: Tries to get the length of the *symbol* named "Hello"
;; (length '"Hello") ; => This will signal a type error.

Modern Lisp implementations are fully Unicode-aware. The length function correctly counts the number of characters, not the number of bytes. This is the behavior you almost always want.

;; The string contains 5 characters, including a Unicode emoji.
(length "Hi 👋 Lisp")
9

It’s useful to know that length is a very fast operation for strings and vectors. Its time complexity is constant, or O(1), because the length is stored with the object itself.

In contrast, calling length on a list is a slower operation. The function must traverse the entire list to count its elements, making it a linear time, or O(n), operation.

;; Fast: O(1) operation
(length "a very very long string...")
;; Slower: O(n) operation
(length '(a very very long list ...))