tags:

views:

209

answers:

2

Hi,

I would like to write an if statement that will do something base on whether a string is empty. For example:

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

In this contrived example, I'm using (is-empty) in place of the real elisp method. What is the right way of doing this?

Thanks

+9  A: 

Since in elisp, a String is an int array, you can use

(= (length user-str) 0)

You can also use (string=) which is usually easier to read

(string= "" user-str)

Equal works as well, but a bit slower:

(equal "" user-str)
mihi
+1  A: 

I'm not sure what the canonical way of testing this is, but you could use the length function and check to see if its greater than zero

(length "abc")
=> 3

(length "")
=> 0

The EmacsWiki elisp cookbook has an example of a trim function if you want to remove whitespace before testing

zimbu668