How to test if a string is empty

If using the primitive TeX if syntax you should always take care to put the test token first before user supplied token, otherwise you have no control over what is being tested:

\documentclass{standalone}
\newcommand{\Test}[3]{%
    \ifnum #1=1 C'est \'egal à 1 \fi
    \if #2v C'est \'egal à v \fi
    \ifx #2v C'est \'egal à v \fi
    \if #3\empty C'est vide \fi
    \ifx #3\empty C'est vide \fi
    }

\begin{document}
\Test{2=2}{aa}{!!}
\end{document}

The 4th test will never test that #3 is empty, if given a single character it tests if it is C.

The exact test you should use depends on your definition of empty. which of these is "empty" where the outer {} are the delimiters of the argument: {} { } {\empty} {\mbox{}}

I normally do something like

 \ifx\som@internal@macro#1\som@internal@macro

where \som@internal@macro is some defined macro in the file that is unlikely to be used in the argument. Then if #1 is empty the test is

 \ifx\som@internal@macro\som@internal@macro

so tests true, If #1 is non empty (and does not start with \som@internal@macro) then it tests false.


Here's David Carlisle's solution in a nice macro called \ifempty. Use it in place of an \if as shown. Make sure to wrap your argument to \ifempty in curly brackets.

\def \ifempty#1{\def\temp{#1} \ifx\temp\empty }

\def \mymacro#1{ \ifempty{#1} empty \else not empty \fi }

\mymacro{something} % prints "not empty"
\mymacro{}          % prints "empty"

As shown by egreg on this thread, using the \ifstrempty command from the etoolbox package, it's possible to test if the given string is empty or not, with the added bonus that linebreaks in the given string won't cause problems.

Here is an example using this command in a macro to test if string #1 is empty :

\usepackage{etoolbox}
\newcommand{\Test}[1]{%
    \ifstrempty{#1}%
        {%
            empty%
        }{%
            not empty%
        }%
}

This macro can also be used to print #2 if #1 is empty and #3 if it's non empty.

\newcommand{\Test}[3]{%
    \ifstrempty{#1}%
    {%
        #2% If #1 is empty
    }{%
        #3% If #1 is not empty
    }%
}

Tags:

Conditionals