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?

3
  • 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
    Commented Oct 22, 2015 at 22:40
  • @egreg Are there some fundamental obstacles from making it expandable?
    – uranix
    Commented Oct 22, 2015 at 22:48
  • It would be quite cumbersome with xstring; I suggest a method with expl3.
    – egreg
    Commented Oct 22, 2015 at 22:50

1 Answer 1

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

1
  • I knew you would come with expl3 :-P
    – user31729
    Commented Oct 22, 2015 at 22:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .