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}
  • Welcome to TeX.SX! Can you tell why you need it? – egreg Nov 23 '14 at 22:36
  • Welcome to TeX.SX! You can have a look at our starter guide to familiarize yourself further with our format. – Martin Schröder Nov 23 '14 at 22:56
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.