[Tex/LaTex] How to test if a string is empty

conditionals

I tried several thing to test if a parameter is empty or equal to a specific carater. How should one proceed ?

By the way, what is the best way to have conditionnal code on a parameter who can have three values : empty, v, h ?

\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{1}{v}{}
\end{document}

Never says vide…

Best Answer

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.

Related Question