I am trying to define a family of commands inside `\tableofcontents`. Here is an example that does not work.

```
\documentclass{book}
\newcounter{foo}

\begin{document}
\tableofcontents
\providecommand{\foo1}{0}
\providecommand{\foo2}{0}

\foo1 \foo2

\stepcounter{foo}
\addtocontents{toc}{\protect\newcommand{\detokenize{\foo}\thefoo}{\thepage}}

text

\stepcounter{foo}
\addtocontents{toc}{\protect\newcommand{\detokenize{\foo}\thefoo}{\thepage}}

text
\end{document}

```

This almost works. The command \detokenize produces an extra space at the end. This results in the `.toc` file having something like `\newcommand{\foo 1}{14}` instead of the desired `\newcommand{\foo1}{14}`.