2009-06-19 69 views
21

我想写一个if语句,根据字符串是否为空来做一些事情。例如:如何检查Emacs Lisp中的字符串是否为空?

(defun prepend-dot-if-not-empty (user-str) 
    (interactive "s") 
    (if (is-empty user-str) 
    (setq user-str (concat "." user-str))) 
    (message user-str)) 

在这个人为的例子中,我使用(is-empty)来代替真正的elisp方法。这样做的正确方法是什么?

感谢

回答

33

因为在elisp的,一个字符串是一个int数组,你可以使用

(= (length user-str) 0) 

您也可以使用(字符串=),这是通常更容易阅读

(string= "" user-str) 

平等的作品也是如此,但有点慢:

(equal "" user-str) 
1

我不知道是什么测试此现象的典型方式是,但是你可以使用长度的功能和检查,看看是否你的字符串的长度大于零:

(length "abc") 
=> 3 
(length "") 
=> 0 

的EmacsWiki elisp的食谱有an example of a trim function如果你想在测试之前删除空格。

3

如果您在代码中大量使用字符串,我强烈建议使用Magnar Sveen的s.el字符串操作库。

s-blank?检查字符串为空:

(s-blank? "") ; => t 
3

我把这个在我utils.lisp:

(defun empty-string-p (string) 
    "Return true if the string is empty or nil. Expects string." 
    (or (null string) 
     (zerop (length (trim string))))) 

然后我做的:

(not (empty-string-p some-string)) 
相关问题