2

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}

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

\begin{document}
\begin{tabular}{cc}\toprule
    \thead{Item & price}\\ \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.

0

2 Answers 2

2

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}

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

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

enter image description here

1
  • 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.
    – Slyrk
    Commented Dec 12, 2016 at 16:58
0

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.)

enter image description here

% !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}
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .