Section and subsection TOC title formatting

I'm putting together a template for college assignments. In order to systematize the writing, I've reformatted the section/subsection titles in the document so they read "Problem #number" and " Answer #number" respectively, without the need for manual entry.

My problem here is that the TOC doesn't put a title for each section and subsection, as there is no argument passed in the command. See this example:

\documentclass{article}
\usepackage{titlesec}

\titleformat{\section}{\large \bfseries}{Problem \arabic{section}}{2em}{}

\begin{document}
\tableofcontents

\section{}
\subsection{}

\end{document}


Produces:

I understand that I can manually add a title for TOC doing:

\section[title]{}


And that I could define a new command that could do this for every section (and for every subsection), like this

\documentclass{article}
\usepackage{titlesec}

\titleformat{\section}{\large \bfseries}{Problem \arabic{section}}{2em}{}

\newcommand{\problem}[1]{\section[Problem \thesection]{#1}}

\begin{document}
\tableofcontents
\problem{}

\end{document}


That produces

But this shows the section number to the left of the title.

Is there a better way to make all titles in the TOC automatically display as in the document?

• Welcome to TeX SX! There is a companion titletoc package, and a\titlecontents command which eases customisation of the table of contents. Apr 22, 2021 at 20:49

I was going to suggest using the exercise package, but discovered a bug in the TOC formatting (which I fixed).

One can reformat the header easily enough, if you don't like centering.

\documentclass{article}
\usepackage{exercise}
\ListOfExerciseInToc
\ExerciseLevelInToc{section}
\def\ExerciseName{Problem}

\makeatletter
\renewcommand{\@@@ExeEnv}{%
\pagebreak[1]\vskip\ExerciseSkipBefore
\@QuestionLevel1
\refstepExecounter
\endgroup\AtBeginExercise}

\renewcommand{\@@@ExeCmd}{%
\ifnum\@QuestionLevel=0
{\partopsep\Exepartopsep \labelsep\Exelabelsep \itemsep \Exesep%
\parsep\Exeparsep \topsep\Exetopsep \labelwidth\Exelabelwidth%
\leftmargin\Exeleftmargin \rightmargin\Exerightmargin}
\else
\termineliste{1}\@EndExeBox
\fi
\@selectExercise
\item\ignorespaces\AtBeginExercise
}
\makeatother

\begin{document}
\tableofcontents
\bigskip\hrule

\section{Normal section}

\begin{Exercise}
Problem text here.
\end{Exercise}

\end{document}


Requires a small modification of the entry of the TOC from \section to suppress the section number.

\documentclass{article}
\usepackage{titlesec}

\titleformat{\section}{\large \bfseries}{Problem \thesection}{2em}{}

\newcommand{\problem}[1]{%
\section[Problem \thesection]{#1}
}

%% from https://tex.stackexchange.com/a/218675/161015
\makeatletter
\let\latexl@section\l@section
\def\l@section#1#2{\begingroup\let\numberline\@gobble\latexl@section{#1}{#2}\endgroup}
\makeatother

\begin{document}
\tableofcontents

\problem{One}

\problem{Two}

\problem{Three}

\end{document}