如何让 \ifcase 与宏参数一起工作

如何让 \ifcase 与宏参数一起工作

在以下示例中,如何让\ifcase语句接受我的\myindex宏作为参数。宏本身可以\myindex正确扩展,但是当我将其用作语句的参数时,会出现错误\ifcase

\documentclass{article}
\usepackage{xstring,ifthen}

\newcommand{\id}{32103210}

\newcommand{\mycommand}[1]{
  \def\myindex{\StrChar{\id}{#1}} %get the #1th character from \id
  My index is \myindex\\%   <-- this works fine

  \ifcase\myindex%   <---- ifcase not working with \myindex but works with other macros
  zero \or  one \or two \or three% <--- expecting zero
  \fi
}

\begin{document}
\mycommand{4}
\end{document}

答案1

\ifcaseTeX 期望 a之后<number>,它会扩展标记,但\StrChar会进行赋值,因此它不会纯粹扩展为 a <number>。使用可选参数:

\documentclass{article}
\usepackage{xstring}

\newcommand{\id}{32103210}

\newcommand{\mycommand}[1]{%
  \StrChar{\id}{#1}[\myindex]% get the #1th character from \id
  My index is \myindex\\%   <-- this works fine
  \ifcase\myindex%   <---- ifcase not working with \myindex but works with other macros
  zero\or one\or two\or three% <--- expecting zero
  \fi
}

\begin{document}
\mycommand{4}
\end{document}

还需小心虚假的空间。

在此处输入图片描述

这样的实现expl3具有完全可扩展的优点:

\documentclass{article}
\usepackage{xparse}

\newcommand{\id}{32103210}

\ExplSyntaxOn
\DeclareExpandableDocumentCommand{\mycommand}{m}
 {
  \str_case_x:nn { \tl_item:Nn \id {#1} }
   {
    {0}{zero}
    {1}{one}
    {2}{two}
   }
 }
\ExplSyntaxOff

\begin{document}
\mycommand{4}
\end{document}

答案2

解决方案stringstrings

\documentclass{article}
\usepackage{stringstrings,ifthen}

\newcommand{\id}{32103210}

\newcommand{\mycommand}[1]{
  \substring[q]{\id}{#1}{#1} %get the #1th character from \id
  My index is \thestring\\%   <-- this works fine

  \ifcase\thestring% 
  zero \or  one \or two \or three%
  \fi
}
\begin{document}
\mycommand{4}
\end{document}

在此处输入图片描述

相关内容