String Functions in Lisp

(defun p (x) (format t "~a~%" x))

(defun main ()
  ;; Here's a sample of the functions available for string manipulation in Lisp.
  ;; We'll use Common Lisp's built-in functions and the cl-ppcre library for 
  ;; regular expression operations.

  (p (format nil "Contains:   ~a" (search "es" "test")))
  (p (format nil "Count:      ~a" (count #\t "test")))
  (p (format nil "HasPrefix:  ~a" (string= "test" "te" :end1 2)))
  (p (format nil "HasSuffix:  ~a" (string= "test" "st" :start1 2)))
  (p (format nil "Index:      ~a" (position #\e "test")))
  (p (format nil "Join:       ~a" (format nil "~{~a~^-~}" '("a" "b"))))
  (p (format nil "Repeat:     ~a" (make-string 5 :initial-element #\a)))
  (p (format nil "Replace:    ~a" (cl-ppcre:regex-replace-all "o" "foo" "0")))
  (p (format nil "Replace:    ~a" (cl-ppcre:regex-replace "o" "foo" "0")))
  (p (format nil "Split:      ~a" (cl-ppcre:split "-" "a-b-c-d-e")))
  (p (format nil "ToLower:    ~a" (string-downcase "TEST")))
  (p (format nil "ToUpper:    ~a" (string-upcase "test"))))

(main)

This Lisp code demonstrates various string operations, similar to the original example. Here’s a breakdown of the functions used:

  1. search: Finds a substring within a string.
  2. count: Counts occurrences of a character in a string.
  3. string= with :end1 or :start1: Checks for prefixes or suffixes.
  4. position: Finds the index of a character in a string.
  5. format with ~{~a~^-~}: Joins strings with a separator.
  6. make-string: Creates a repeated string.
  7. cl-ppcre:regex-replace-all and cl-ppcre:regex-replace: Replace substrings.
  8. cl-ppcre:split: Splits a string into a list.
  9. string-downcase and string-upcase: Convert string case.

To run this program, save it as string-functions.lisp and use your Lisp interpreter. For example, with SBCL:

$ sbcl --load string-functions.lisp

The output will be similar to:

Contains:   1
Count:      2
HasPrefix:  T
HasSuffix:  T
Index:      1
Join:       a-b
Repeat:     aaaaa
Replace:    f00
Replace:    f0o
Split:      (a b c d e)
ToLower:    test
ToUpper:    TEST

Note that Lisp uses zero-based indexing, so the “Index” result is 1 (second position) for the ’e’ in “test”. Also, Lisp’s boolean values are T (true) and NIL (false).

The cl-ppcre library is used for regular expression operations, which may need to be installed separately depending on your Lisp environment.