# How to split input string in a LaTeX command?

I would like a new command: \myfunc{string}, where string is something like: "a,b,x,y,x" and the effect of the command should be the following: \func{a}\func{b}\func{x}\func{y}\func{x}, where \func{} is another predefined function. How to do this?

This is very easy with xparse:

\documentclass{article}
\usepackage{xparse}

\NewDocumentCommand{\myfunc}{ >{\SplitList{,}} m }{%
\ProcessList{#1}{\func}%
}

\NewDocumentCommand{\func}{m}{%
\fbox{#1} % a space follows
}

\begin{document}

\myfunc{a,b,c,x,y,z}

\end{document}


Note that \func can be defined in whatever way you like, also with \newcommand. What's important is that it has one argument.

You can also add code before \ProcessList{#1}{\func} and after it.

Note that you're not restricted to commas as separators, because you specify it at definition time.

Another advantage is that \SplitList automatically trims leading and trailing spaces around items, so the output from

\myfunc{ a , b,c ,x,y , z }


will be the same, contrary to other lower level approaches.

LaTeX has a built in command for iterating over comma separated lists:

\documentclass{article}

\makeatletter
\newcommand\myfunc[1]{\@for\tmp:=#1\do{\func{\tmp}}}

\let\func\fbox

\begin{document}

\myfunc{a,b,c,d}

\end{document}