在以下示例中,如何让\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
\ifcase
TeX 期望 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}