5

I'd like to know how one can change the table's default empty cell space to something else when the cell has nothing written in it.

E.g:

\begin{table}
\begin{tabular}{l l l l}
1 & 2 & 3 & 4\\
& x & x
\end{tabular}
\end{table}

Would result in this:

1|2|3|4
 |x|x|

But what I'm aiming for is to replace the blank cell for, let's say, 0. So something like this:

1|2|3|4
0|x|x|0

Thanks.

-- Edit --

MWE:

\documentclass{article}

\begin{document}

\begin{table}[htbp]
\begin{tabular}{l l l l}
1 & 2 & 3 & 4 \\
& x & x
\end{tabular}
\end{table}

\end{document}
albert
  • 937
gdx
  • 53

1 Answers1

5

You can do it with the collcell package:

\documentclass{article}
\usepackage{collcell}

\newcolumntype{F}[1]{>{\collectcell\fillempty}#1<{\endcollectcell}}
\newcommand{\fillempty}[1]{%
  \if\relax\detokenize{#1}\relax
    0%
  \else
    #1%
  \fi
}

\begin{document}

\begin{tabular}{ *{4}{F{l}} }
1 & 2 & 3 & 4 \\
  & x & x &   \\
\multicolumn{1}{l}{} & y & y
\end{tabular}

\end{document}

The third row shows two features: the first is that with \multicolumn{1}{l}{} you can override the filling; the second is that if you don't have an explicit empty cell, the filling is not performed, because TeX doesn't add trailing cells on a row.

enter image description here

See What does \ifx\\#1\\ stand for? for the \if\relax\detokenize{#1}\relax trick.

egreg
  • 1,121,712