Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if character is in string

Tags:

common-lisp

In Common Lisp, is there a predicate to test whether a given character is part of a string? Or more generally, if an element is a member of a vector?

Something like:

(char-in #\o "foo")

I was able to implement it as

(defun char-in (c s)
  (member c (coerce s 'list)))

Is there a better way?

like image 871
Gradient Avatar asked Dec 18 '22 21:12

Gradient


1 Answers

Strings are vectors. Vectors are sequences.

Strings are vectors and sequences. So all operations for them apply:

Find an item:

CL-USER 59 > (find #\X "fooXbar")
#\X

CL-USER 60 > (find #\x "fooXbar")
NIL

Find the position of an item:

CL-USER 61 > (position #\x "fooXbar")
NIL

CL-USER 62 > (position #\X "fooXbar")
3

Search for a subsequence:

CL-USER 63 > (search "X" "fooXbar")
3

CL-USER 64 > (search "x" "fooXbar")
NIL

Default test is EQL

All functions use EQL as the default test, but you can use another one - for example a case-insensitive find would be:

CL-USER 65 > (find #\x "fooXbar" :test #'char-equal)
#\X
like image 155
Rainer Joswig Avatar answered Feb 08 '23 16:02

Rainer Joswig