For loop with EqCase, StrLeft is not working

\StrLeft is not expandable since it has an optional argument for a macro to which the \StrLeft content is stored at the end. A possible solution is to remove the \StrLeft from the \IfEqCase command and use this optional argument, storing to, say, \foostring and using \foostring in the \IfEqCase command.

The empty line almost at the end in the code of \testit is on purpose.

\documentclass{article}
\usepackage{xstring}

\begin{document}

\makeatletter
\newcommand{\testit}[1]{%
  \@for\@tag:=#1\do%
  {%
    \StrLeft{\@tag}{1}[\foostring]
    \IfEqCase{\foostring}%
    {%
      {a}{First letter is a}%
      {b}{First letter is b}%
    }%

  }%
}

\testit{aa,ab,ba}
\makeatother

\end{document}

enter image description here


You may enjoy a different way to solve your problem:

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\test}{m}
 {
  \clist_map_inline:nn { #1 }
   {
    \str_case_e:nnF { \tl_head:n { ##1 } }
     {
      {a}{First~letter~is~a}
      {b}{First~letter~is~b}
     }
     {First~letter~is~neither~a~nor~b}
    \par
   }
 }
\ExplSyntaxOff

\begin{document}

\test{aa,ab , bc, xy}

\end{document}

The \clist_map_inline:nn function is the counterpart of \@for, but has some advantages over it:

  • it ignores leading and trailing spaces;
  • it doesn't require a dummy control sequence, as the current item is denoted by #1 (here ##1 because we're calling it in the body of a definition).

The function \str_case_e:nnF is the counterpart of \IfEqCase; with \tl_head:n { ##1 } we isolate the first token in the current item of the comma separated list (that is, it does the job of \StrLeft).

enter image description here

In a real world example, it could be possible to avoid ~ and use spaces, but more information about how you plan to use the functions is necessary.

Tags:

Macros

Xstring