3

With the following command the tokens can be counted in a list. How can I count only the number of commas in the list?

\documentclass{article}
\usepackage{xfp}

\begin{document}
\ExplSyntaxOn
\NewDocumentCommand{\CountComma}{m}{%
\tl_count:n {#1}
}
\ExplSyntaxOff

\CountComma{1/!/?,2/1/0,3+2/1*2,4/0,5/1/0,6/0,A/B/1,8/0,9/0}

\end{document}

1 Answers1

2

This is only a solution for the case that commas do not follow each other without element between or do not occur inside {} pairs:

\clist_count:n counts the number of elements in a comma separated list, however, {1,2} would give 2 instead of 1, so wrap \int_eval:n{\clist_count:n {#1} -1} around this.

Using the hint by egreg: \int_max:nn {\clist_count:n {#1} -1}{0} is shorter

Of course the \CountComma macro should be expandable, so use \NewExpandableDocumentCommand.

\documentclass{article}
\usepackage{xfp}


\ExplSyntaxOn
\NewExpandableDocumentCommand{\CountComma}{m}{% Should be expandable!
    \int_max:nn { \clist_count:n {#1}-1 } {0}
}
\ExplSyntaxOff


\begin{document}

\CountComma{1/!/?,2/1/0,3+2/1*2,4/0,5/1/0,6/0,A/B/1,8/0,9/0}

\CountComma{1,2}

\CountComma{4}

\edef\foo{\CountComma{1,2,3}}

Foo is \foo

\end{document}