5

How can I make the \ifcase statement accept my \myindex macro as an argument in the following example. On its own, the \myindex macro expands correctly, however, I get an error when I use it as the argument to the \ifcase statement.

\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}

2 Answers 2

5

After \ifcase TeX expects a <number> so it expands tokens, but \StrChar does assignments, so it doesn't purely expand to a <number>. Use the optional argument:

\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}

Be also careful with spurious spaces.

enter image description here

An implementation with expl3 that has the advantage of being fully expandable:

\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}
0
1

A solution with 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}

enter image description here

You must log in to answer this question.

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