命令中参数的数量可变

命令中参数的数量可变

代码

\documentclass{article}
\newcommand*\test[2]{#1\textsuperscript{#2}}
\begin{document}
The player ended as no.~\test{1}{} and her friend came in \test{2}{nd}.
\end{document}

输出

输出

问题

我怎样才能更改\test命令以便能够在一个或两个参数之间切换?

(我希望能够写作\test{1}而不是\test{1}{}。)

答案1

我建议使用替代界面*(比如说):

在此处输入图片描述

\documentclass{article}

\usepackage{fmtcount}

\makeatletter
\newcommand{\@test}[1]{#1}
\newcommand{\@@test}[1]{\ordinalnum{#1}}
\newcommand{\test}{\@ifstar\@test\@@test}
\makeatother

\begin{document}

\test{1} \test*{1}

\test{2} \test*{2}

\test{11} \test{12} \test{21}
\end{document}

上述命令定义也可以使用xparse

\usepackage{xparse}
\NewDocumentCommand{\test}{s m}
  {\IfBooleanTF{#1}{#2}{\ordinalnum{#2}}}

答案2

使用可选参数说明符xparse可以轻松完成该功能,但在我看来,可选参数应该用,即使用!g[...]o

\documentclass{article}
\usepackage{xparse}


\NewDocumentCommand{\test}{mg}{#1\IfValueT{#2}{\textsuperscript{#2}}}
\begin{document}
The player ended as no.~\test{1} and her friend came as \test{2}{nd}.
\end{document}

答案3

\documentclass[a4paper]{article}
\newcommand\test[2][]{#2\ifx\relax#1\relax\else\textsuperscript{#1}\fi}
\begin{document}
The player ended as no.~\test{1} and her friend came ind \test[nd]{2}.
\end{document}

相关内容