39

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

1
  • Your code is better rewritten to (message "%s" (if (is-empty user-str) "." user-str)).
    – Stefan
    Commented Oct 19, 2018 at 1:21

5 Answers 5

55

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)
1
  • 1
    Are you sure equal is slower? Last time I looked at this (many years ago), it was somewhere between "identicall" and "a bit faster".
    – Stefan
    Commented Oct 19, 2018 at 1:19
10

Starting in emacs 24.4, there are two different functions available for you to call, depending on what you mean by 'empty'.

(string-empty-p " ")
nil

(string-blank-p " ")
0

I'm having trouble finding docs to link to, but emacsredux.com has more information.

If you get the error Symbol's function definition is void., include (require 'subr-x) in the initialization file (it's a package for trimming and string manipulation).

2
  • I have Emacs 26.3 and both calls throw Symbol's function definition is void.
    – emonigma
    Commented Nov 27, 2019 at 20:50
  • 1
    @miguelmorin: Try putting (require 'subr-x) somewhere earlier in your file. That solved the problem for me.
    – Cadence
    Commented Sep 28, 2020 at 12:14
7

If you work with strings heavily in your code, i strongly recommend using Magnar Sveen's s.el string manipulation library.

s-blank? checks if the string is empty:

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

I keep this one in my utils.lisp:

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

then I do:

(not (empty-string-p some-string))
3

I'm not sure what the canonical way of testing this is, but you could use the length function and check to see if your string's length is 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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.