使用多个 \ifnumequal 的空白问题

使用多个 \ifnumequal 的空白问题

我试图根据单个数字输入生成略有不同的文档。但是当我使用多个 \ifnumequal 命令来获取正确的文本时,它会在文本周围产生非常奇怪的空白。你能帮忙吗?我尝试过(如下所示)一个接一个地使用 \ifnumequal,并以嵌套形式,但仍然出现空白问题。

这是一个重现该问题的小例子。

\documentclass{article}
\usepackage{etoolbox}
\newcounter{N}

\begin{document}

\setcounter{N}{1}
The counter N has been set to 
\ifnumequal{\value{N}}{1}{\emph{one}}{}
\ifnumequal{\value{N}}{2}{\emph{two}}{}
\ifnumequal{\value{N}}{3}{\emph{three}}{}
which is nice.

\setcounter{N}{2}
The counter N has been set to 
\ifnumequal{\value{N}}{1}{\emph{one}}{}
\ifnumequal{\value{N}}{2}{\emph{two}}{}
\ifnumequal{\value{N}}{3}{\emph{three}}{}
which is nice.

\setcounter{N}{3}
The counter N has been set to 
\ifnumequal{\value{N}}{1}{\emph{one}}{}
\ifnumequal{\value{N}}{2}{\emph{two}}{}
\ifnumequal{\value{N}}{3}{\emph{three}}{}
which is nice.

\setcounter{N}{3}
The counter N has been set to 
\ifnumequal{\value{N}}{1}{\emph{one}}{
\ifnumequal{\value{N}}{2}{\emph{two}}{
\ifnumequal{\value{N}}{3}{\emph{three}}{}}}
which is nice.

\end{document}

答案1

在 TeX 中,行尾算作空格,所以你会得到四个而不是一个,所以你应该输入

The counter N has been set to 
\ifnumequal{\value{N}}{1}{\emph{one}}{}%
\ifnumequal{\value{N}}{2}{\emph{two}}{}%
\ifnumequal{\value{N}}{3}{\emph{three}}{}
which is nice.

顺便说一下,还有其他方法可以达到相同的效果:

The counter N has been set to
\ifcase\value{N}\or
\emph{one}\or
\emph{two}\or
\emph{three}\fi
which is nice

语法是

\ifcase<number><text for case 0>\or<text for case 1>\or...\else<none of the above>\fi

\else部分为可选部分。

当然,您想隐藏宏中的代码:

\newcommand{\testcount}[1]{%
  \ifnumequal{\value{#1}{1}{\emph{one}}{}%
  \ifnumequal{\value{#1}{1}{\emph{two}}{}%
  \ifnumequal{\value{#1}{1}{\emph{three}}{}%
}

并输入The counter N has been set to \testcount{N} which is nice

你可以得到更灵活的宏expl3

\usepackage{expl3}
\ExplSyntaxOn
\NewDocumentCommand{\testcount}{m}
 {
  \int_case:nnF { \value{#1} }
   {
    {1}{\emph{one}}
    {2}{\emph{two}}
    {3}{\emph{three}}
    {42}{\emph{the answer}}
   }
   {\textbf{A weird value}}
 }
\ExplSyntaxOff

相关内容