38

How to check if a string s1 is a substring of another string s2?

For example (test-substring "f t" "df tj") --> t, (test-substring "ft" "df tj") --> nil.

Name
  • 7,689
  • 4
  • 38
  • 84

2 Answers2

53

The standard Emacs Lisp approach is regular expression matching:

(string-match-p (regexp-quote needle) haystack)
26

cl-search can do that (and also returns the index of the substring, if found):

ELISP> (cl-search "f t" "df tj")
1 (#o1, #x1, ?\C-a)
ELISP> (cl-search "ft" "df tj")
nil
legoscia
  • 6,012
  • 29
  • 54