Test if the value of a counter belongs to a given list of values
\documentclass{article}
\usepackage{xifthen}
\newcounter{mycounter}
\setcounter{mycounter}{17}
\newcommand{\test}[2]{\ifthenelse{\isin{|#1|}{#2}}{Yes}{No}}
\begin{document}
\test{17}{|15|17|19|} returns Yes
\test{18}{|15|17|19|} returns No
\edef\tmp{\themycounter}
\expandafter\test\expandafter{\tmp}{|15|17|19|} returns Yes
\end{document}
This approach can be directly incorporated into the macro:
\documentclass{article}
\usepackage{xifthen}
\newcounter{mycounter}
\setcounter{mycounter}{17}
\newcommand{\test}[2]{%
\edef\tmp{#1}%
\ifthenelse{\expandafter\isin\expandafter{\expandafter|\tmp|}{#2}}{Yes}{No}%
}
\begin{document}
\test{17}{|15|17|19|} returns Yes
\test{18}{|15|17|19|} returns No
\test{\themycounter}{|15|17|19|} returns Yes
\end{document}
And for a completely different approach, here I use the listofitems
package to parse argument #2
using expanded argument |#1|
as the separator. If I get more than 1 element in the resulting array list, then one may conclude that the separator was found in #2
.
\documentclass{article}
\usepackage{listofitems}
\newcounter{mycounter}
\newcommand{\test}[2]{%
\edef\tmp{#1}%
\expandafter\setsepchar\expandafter{\expandafter{\expandafter|\tmp|}}%
\readlist\tmparray{#2}
\ifnum\tmparraylen>1\relax Yes\else No\fi%
}
\begin{document}
\test{17}{|15|17|19|} returns Yes
\test{18}{|15|17|19|} returns No
\setcounter{mycounter}{17}
\test{\themycounter}{|15|17|19|} returns Yes
\end{document}
You can use pdfTeX's \pdfmatch{<strA>}{<strB>}
which returns 1 if <strA>
is found in <strB>
. Pattern matching with punctuation requires some care. This is expandable:
\documentclass{article}
\newcommand{\test}[2]{\ifnum\pdfmatch{[|]#1[|]}{#2}=1 Yes\else No\fi}
\begin{document}
\verb!\test{17}{|15|17|19|}! returns: \test{17}{|15|17|19|}
\verb!\test{18}{|15|17|19|}! returns: \test{18}{|15|17|19|}
\newcounter{test}
\setcounter{test}{17}%
\verb!\test{\thetest}{|15|17|19|}! returns: \test{\thetest}{|15|17|19|}
\setcounter{test}{18}%
\verb!\test{\thetest}{|15|17|19|}! returns: \test{\thetest}{|15|17|19|}
\end{document}
The above pattern matching for \thetest
works because \thetest
expands to \arabic{test}
(by default). If this is not the case, you can use \arabic{test}
directly.
Or use package xstring
, which has all manner of neat tests built in:
\documentclass{article}
\usepackage{xstring}
\newcounter{sausage}
\setcounter{sausage}{18}
\begin{document}
\IfSubStr{|17|18|19|}{|\arabic{sausage}|}{true}{false}
\IfSubStr{|17|15|19|}{|\arabic{sausage}|}{true}{false}
\end{document}