不计“&”符号的表格

不计“&”符号的表格

我想要一个像这样的命令

\mytable{4}{ a & b & c & d & e & f}

相当于

\begin{tabular}{cccc}
a & b & c & d\\
e & f\\
\end{tabular}

\mytable{2}{ a & b & c & d & e & f}

相当于

\begin{tabular}{cc}
a & b\\
c & d\\
e & f\\
\end{tabular}

答案1

这是一个使用分隔宏和计数器的解决方案。

代码

\documentclass{article}
\newcounter{mytable@count}
\makeatletter
\newcommand{\mytable}[2]{%
  \edef\mytable@count@{#1}%
  \setcounter{mytable@count}{0}%
  \begin{tabular}{*{#1}{c}}
    \strip@ampersand#2&\@nil
  \end{tabular}
}
\def\strip@ampersand#1&#2\@nil{%
  #1%
  \if\relax\detokenize{#2}\relax
    \expandafter\@gobble
  \else
    \expandafter\@firstofone
  \fi
  {%
    \stepcounter{mytable@count}%
    \ifnum\value{mytable@count}<\mytable@count@\relax
      \expandafter\@firstoftwo
    \else
      \expandafter\@secondoftwo
    \fi
    {&}
    {\\\noalign{\setcounter{mytable@count}{0}}}%
    \strip@ampersand#2\@nil
  }%
}
\makeatother

\begin{document}
\mytable{4}{ a & b & c & d & e & f}

\hrulefill

\mytable{2}{ a & b & c & d & e & f}
\end{document}

输出

在此处输入图片描述

答案2

一个expl3解决方案。我添加了一个可选参数,用于指定不同的条目分隔符以及不同的列对齐方式。

\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\mytable}{O{&} m O{c} m}
 {% #1 = inner delimiter (optional}
  % #2 = number of columns
  % #3 = alignment (optional)
  % #4 = table body
  \egreg_mytable:nnnn { #1 } { #2 } { #3 } { #4 }
 }

\seq_new:N \l__egreg_tablebody_seq
\tl_new:N \l__egreg_tablebody_tl
\int_new:N \l__egreg_step_int

\cs_new_protected:Npn \egreg_mytable:nnnn #1 #2 #3 #4
 {
  % store the body in a sequence
  \seq_set_split:Nnn \l__egreg_tablebody_seq { #1 } { #4 }
  \int_zero:N \l__egreg_step_int
  \tl_clear:N \l__egreg_tablebody_tl
  % build the real table body
  \seq_map_inline:Nn \l__egreg_tablebody_seq
   {
    % increment the counter
    \int_incr:N \l__egreg_step_int
    % add an entry
    \tl_put_right:Nn \l__egreg_tablebody_tl { ##1 }
    % add \\ if we are done for a row, else add &
    % we just compute the remainder of the division by #2
    \int_compare:nTF { \int_mod:nn { \l__egreg_step_int } { #2 } = 0 }
     { \tl_put_right:Nn \l__egreg_tablebody_tl { \\ } }
     { \tl_put_right:Nn \l__egreg_tablebody_tl { & } }
   }
  % produce the table
  \begin{tabular}{*{#2}{#3}}
  \l__egreg_tablebody_tl
  \end{tabular}
 }

\ExplSyntaxOff
\begin{document}

\mytable{4}{ a & b & c & d & e & f}

\medskip

\mytable{2}{ a & b & c & d & e & f}

\medskip

\mytable[,]{3}{a, b, c, d, e, f}

\medskip

\mytable[;]{3}[l]{aaa; bb; ccc; dddddd; e; f}

\medskip

\mytable[;]{3}[lr]{aaa; bb; ccc; dddddd; e; f}

\end{document}

在此处输入图片描述

相关内容