About me

About me

Feeds

RSS feed

Testing for a prefix

2nd August 2015

A fairly common task is to test for the presence of a prefix in a string. For example we might want to do:

(check-prefix "www.lispology.com" "www")

The first way I implemented this was the obvious approach:

(defun check-prefix (string prefix)
  (string= string prefix :end1 (length prefix)))

 and this seems to work fine:

> (check-prefix "www.lispology.com" "www")
T

but it comes unstuck if we give it a short string:

> (check-prefix "no" "www")

Error: The index 3 is out of range for sequence "no".

The fix is to check the length of the string:

(defun check-prefix (string prefix)
  (and
   (>= (length string) (length prefix))
   (string= string prefix :end1 (length prefix))))

but the routine is now becoming a bit inelegant.

Better solution

The following simpler solution occurred to me, taking advantage of the fact that Lisp's sequence operators ignore elements beyond the shortest sequence, and work with characters as well as lists:

(defun check-prefix (string prefix)
  (every #'char= string prefix))

Trying it out:

IDENTIFIER 17 : 5 > (check-prefix "www.lispology.com" "www")
T

IDENTIFIER 16 : 5 > (check-prefix "no" "www")
NIL

blog comments powered by Disqus