Update counter in newcommand without printing the result of the command

countersxstring

In the following MWE I want to update my counter via a custom command \noofwords, but it

  • writes an error on line 25: Missing number, treated as zero. \noofwords
  • writes the PDF otherwise just fine
  • the new value of the counter (at least I thought it would be its value) gets printed in the document when I call the command \noofwords (which is 2 and therefore 1 less than expected, as it should be 3)
  • writes the initial value of \thenoofwords (which is 1) instead of the updated value (which should be 3 as mentioned before)

Why is that and what would be a way to solve or circumvent this problem?

MWE:

\documentclass{scrreprt}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{xstring}

\newcommand{\test}{word1, word2, word3}

\newcounter{noofcommas}
\setcounter{noofcommas}{1}

\newcounter{noofwords}
\setcounter{noofcommas}{1}

\newcommand{\noofwords}{ %
    \setcounter{noofwords}{
    \setcounter{noofcommas}{ %
        \StrCount{\test}{,}}}
    \refstepcounter{noofwords}}

\begin{document}
    
\thenoofcommas

\noofwords

\thenoofwords

\end{document}

Best Answer

The commands of xstring have an optional argument where you can add a command which stores the result. This can then be used in a \setcounter:

\documentclass{scrreprt}

\usepackage[T1]{fontenc}
\usepackage{xstring}

\newcommand{\test}{word1, word2, word3}

\newcounter{noofcommas}
\setcounter{noofcommas}{1}

\newcounter{noofwords}
\setcounter{noofcommas}{1}


\begin{document}

\StrCount{\test}{,}[\numofcommas]
\setcounter{noofcommas}{\numofcommas}

\thenoofcommas

\end{document}

I removed the inputenc line as it is not longer needed in a current LaTeX.

Related Question