How to check if a value is not equal using TeX conditionals?
You can define a command that expands to "apple", another that expands to whatever you want to test, and then use \ifx
. Here's a latex file that demonstrates this:
\documentclass{article}
\begin{document}
\def\appleref{apple}
\def\testit#1{%
\def\temp{#1}%
\ifx\temp\appleref
Yes, it's apple.
\else
No, it's #1.
\fi
}
apple: \testit{apple}
pear: \testit{pear}
\def\fakeapple{apple}
fakeapple: \testit{\fakeapple}
\end{document}
Edit: tohecz points out in a comment that if you change \def\temp{#1}
to \edef\temp{#1}
, then \fakeapple
(which is a macro that expands to "apple") would test as being equal to "apple".
ConTeXt provides a \doif...
series of macros to do string comparisons. See the ConTeXt wiki for details. For example, if you want check if #1
is the same as a previously defined macro \fakeapple
, then you can use:
\def\checkapple#1%
{\doifnot\fakeapple{#1}
{It is not an apple, it is #1}}
Under pdfTeX you can perform string comparisons using \pdfstrcmp{<strA>}{<strB>}
. From the pdfTeX user manual:
\pdfstrcmp{<general text>}{<general text>}
(expandable)This command compares two strings and expands to
0
if the strings are equal, to-1
if the first string ranks before the second, and to1
otherwise. The primitive was introduced in pdfTEX 1.30.0.
\documentclass{article}
\begin{document}
\def\appleref{apple}
\def\testit#1{%
\ifnum\pdfstrcmp{#1}{apple}=0
Yes, it's apple.
\else
No, it's #1.
\fi
}
apple: \testit{apple}
pear: \testit{pear}
\def\fakeapple{apple}
fakeapple: \testit{\fakeapple}
\end{document}