[Tex/LaTex] Programmatically setting a counter to a substring

counterserrorsstringstex-core

I'm trying to set a counter based on the name of the current job. I've got the number I need by doing something like \substring{\jobname}{5}{5}} using the stringstrings package, and if I just output that into the document, I see the right value. However, naively trying to use it as an argument to \setcounter fails with the error "Missing number, treated as zero." I don't know enough about TeX internals to speculate intelligently on what's going on here, so I'll simply ask: How should I make this work?

Minimal example (save this as file3-example.tex):

\documentclass{article}
\usepackage{stringstrings}
\begin{document}
% \substring{\jobname}{5}{5} % this outputs 3
\setcounter{section}{\substring{\jobname}{5}{5}} % this fails
\section{Foo}
\end{document}

Best Answer

As already stated the \setcounter{section}{..} must only include material which expands to a number. The string manipulation macro requires assignments internally, I guess, which makes it not fully expandable, so it causes an error.

I would recommend the xstring package instead. Its macros can also store the returned string into a (then expandable!) macro:

\documentclass{article}
\usepackage{xstring}
\begin{document}
\StrChar{\jobname}{5}[\mysubstring]%
% Or: (useful if the number would be two digits long
%\StrMid{\jobname}{5}{5}[\mysubstring]%
\setcounter{section}{\mysubstring}%
\addtocounter{section}{-1}% because it is incremented in \section
\section{Foo}
\end{document}

Note the egreg's answer is very fine and does not require a most likely big package to be loaded. I just wanted to show a LaTeX-highlevel solution for people which prefer that.

Related Question