# Replacing special characters with StrSubstitute

Is there a way to replace special characters in a string with \StrSubstitute? For example, how can I make something like \StrSubstitute{#1}{&}{&\bfseries } work?

I am asking because I was trying to define a macro that boldens a row of a table along the lines of

\newcommand{\thead}[1]{\bfseries \StrSubstitute{#1}{&}{&\bfseries }}


so that you could write in a document

\usepackage{booktabs, xstring}

\begin{document}
\begin{tabular}{cc}\toprule
foo & 1\\
bar & 2\\ \bottomrule
\end{tabular}
\end{document}


I noticed that there is a solution for that specific problem here: Make first row of table all bold, by replacing cc by $c^c. I was still wondering about how to replace special characters with the xstring package in its own right, maybe for other uses in the future. Also, a macro that wouldn't require changing cc to $c^c might be preferred by some.

You have to apply \noexpandarg, or \bfseries won't survive. You also have to delay the expansion after a group has ended, or TeX will see & too early, ending a cell before \StrSubstitute has performed its duty.

\documentclass{article}
\usepackage{booktabs, xstring}

\bfseries
\noexpandarg
{\StrSubstitute{#1}{&}{&\bfseries }[\temp]\expandafter}\temp
\\ \midrule
}

\begin{document}
\begin{tabular}{cc}
\toprule
foo & 1\\
bar & 2\\
\bottomrule
\end{tabular}
\end{document}


• Thank you very much! That is precisely what I was looking for. I expected it to have something to do with the expandarg modes, but couldn't figure it out by myself. Dec 12 '16 at 16:58

If you're willing and able to use LuaLaTeX to compile your LaTeX document, here's a solution that makes use of some of Lua's powerful string functions. (The user macro is called \boldrow; the name \thead might conflict with the macro of the makecell package.)

% !TeX program = lualatex
\documentclass{article}
\usepackage{booktabs}
\usepackage{luacode} % for 'luacode' environment and '\luastringN' macro
\begin{luacode}
function boldrow ( s )
tex.sprint ( "\\bfseries " .. string.gsub ( s , "&" , "&\\bfseries" ) )
end
\end{luacode}
\newcommand\boldrow[1]{\directlua{boldrow(\luastringN{#1})}}

\begin{document}
\begin{tabular}{cc}
\toprule
\boldrow{Item & price}\\
\midrule
foo & 1\\
bar & 2\\
\bottomrule
\end{tabular}
\end{document}
`