1

Upon compiling this minimal example

\documentclass[12pt]{article}

\usepackage{xstring}

\newcommand{\digit}[1]{
    \IfStrEqCase{#1}{%
        {0}{zero}%
        {1}{one}%
        {2}{two}%
    }[many]%
}

\begin{document}
\digit{1}
\digit{2}
\digit{3}
\digit{\StrChar{456}{2}}
\end{document}

I get the following error

! TeX capacity exceeded, sorry [input stack size=5000].
\@testopt #1#2->\kernel@ifnextchar [{#1
                                       }{#1[{#2}]}

Is it possible to make this code work?

  • 2
    No, it's not possible like this: \StrChar{456}{2} is not a digit, but a set of (unexpandable) instruction to possibly produce one. – egreg Oct 22 '15 at 22:40
  • @egreg Are there some fundamental obstacles from making it expandable? – uranix Oct 22 '15 at 22:48
  • It would be quite cumbersome with xstring; I suggest a method with expl3. – egreg Oct 22 '15 at 22:50
2

\StrChar{456}{2} is not a digit, but a set of instructions that (possibly) produces a digit. Instead, \IfEqStrCase needs an explicit digit, after full expansion, which is not possible from \StrChar.

You can do it with expl3 (called via xparse):

\documentclass[12pt]{article}

\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\digit}{m}
 {
  \str_case:fnF { #1 }
   {
    {0}{zero}%
    {1}{one}%
    {2}{two}%
   }
   {many}
 }
\cs_generate_variant:Nn \str_case:nnF { f }

\DeclareExpandableDocumentCommand{\extract}{mm}
 {
  \tl_item:nn { #1 } { #2 }
 }
\ExplSyntaxOff

\begin{document}

\digit{1}
\digit{2}
\digit{3}
\digit{\extract{456}{2}}

\end{document}

enter image description here

  • I knew you would come with expl3 :-P – user31729 Oct 22 '15 at 22:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.