是否有一个函数可以检查字符串是否以某个子字符串结尾? Python 有 endswith
:
>>> "victory".endswith("tory")
True
最佳答案
只需安装 s.el
字符串操作库并使用它的 s-suffix?
谓词:
(s-suffix? "turn." "...when it ain't your turn.") ; => t
但是如果你拒绝使用这个库,你就必须编写自己的函数。有
string-prefix-p
,它类似于 Python 的 str.startswith
, 在 subr.el
,它只是 compare-strings
的包装器.根据 Emacs 24.3 changelog :** New function `string-prefix-p'.
(This was actually added in Emacs 23.2 but was not advertised at the time.)
string-suffix-p
是 added only in Emacs 24.4 ,所以对于早期版本,我写道:(defun string-suffix-p (str1 str2 &optional ignore-case)
(let ((begin2 (- (length str2) (length str1)))
(end2 (length str2)))
(when (< begin2 0) (setq begin2 0))
(eq t (compare-strings str1 nil nil
str2 begin2 end2
ignore-case))))
(when (< begin2 0) (setq begin2 0))
是一种解决方法,因为如果您将负数传递给 compare-strings
,它会吐出 *** Eval error *** Wrong type argument: wholenump, -1
.如果您对函数进行字节编译,它的运行速度会比 yves Baumes 快解决方案,即使
string-match
是一个 C 函数。ELISP> (setq str1 "miss."
str2 "Ayo, lesson here, Bey. You come at the king, you best not miss.")
ELISP> (benchmark-run 1000000 (string-suffix-p str1 str2))
(4.697675135000001 31 2.789847821000066)
ELISP> (byte-compile 'string-suffix-p)
ELISP> (benchmark-run 1000000 (string-suffix-p str1 str2))
(0.43636462600000003 0 0.0)
ELISP> (benchmark-run 1000000 (string-match "miss\.$" str2))
(1.3447664240000001 0 0.0)
关于string - 检查字符串是否以 Emacs Lisp 中的后缀结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22403751/