我在搜索某物时看到了这些命令。我想知道我们是否可以增加数字如果状况。
就像是如果{0} =,如果{1} = b,如果{2} = c,如果{3} = dETC。
\newcommand{mycommand}[1]{
\if{#1 != 0}
Some text, because it's nonzero
\else
Some other text, because it's zero
\fi
}
\mycommand{0}
\mycommand{1}
答案1
你可以做得更好:\newcasecommand
它可以处理任意标签,而不仅仅是数字。
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\newcasecommand}{ m m O{No~default~value} }
{
\cs_new_protected:Npn #1 ##1
{
\str_case:nnF { ##1 } { #2 } { #3 }
}
}
\ExplSyntaxOff
\newcasecommand{\mycommand}{%
{0}{The number is zero}
{1}{The number is one}
{x}{We have x}
}[Boo!]
\begin{document}
\mycommand{0}
\mycommand{1}
\mycommand{x}
\mycommand{foo}
\end{document}
语法是
\newcasecommand{<command>}{
{<string-a>}{<text for case a>}
{<string-b>}{<text for case b>}
...
}[<text for no match>]
最后一个参数是可选的;默认是打印信息文本,可以转换为警告。
答案2
你可能会喜欢\ifcase ...\or...\fi
这种情况 - 这是一个完整的示例
% arara: pdflatex
% !arara: indent: {overwrite: yes}
\documentclass{article}
\newcommand{\mycommand}[1]{%
\ifcase#1
Some text, because it's zero
\or
Some other text, because it's one
\or
Some other text, because it's two
% keep going if you need 3, 4, 5, etc
\fi
}
\begin{document}
\mycommand{0}\par
\mycommand{1}\par
\mycommand{2}
\end{document}