How to repeat text

There is really no need to reinvent the wheel. There are a number of looping packages out there that you can use to iterate over a sequence. I've used multido below:

enter image description here

\documentclass{article}
\usepackage{multido}% http://ctan.org/pkg/multido
\makeatletter
\newcommand{\append}[3]{ % #1 = start of text, #2 = text to repeat, #3 = number of repetitions
 \def\@looop{#1}% start of text
 \ifnum#3>0\multido{\iA=1+1}{#3}{\g@addto@macro\@looop{#2}}\fi% text to repeat
 \@looop}% Execute
\makeatother
\begin{document}

\noindent\append{c}{c}{0}

\noindent\append{c}{c}{1}

\noindent\append{c}{c}{2}

\noindent\append{c}{c}{3}

\noindent\begin{tabular}{*{3}{c}}
  1 & 2 & 3 \\
  \append{start}{&test}{1} \\
  \append{start}{&test}{2}
\end{tabular}

\end{document}

The idea is to construct a macro \@looop that contains the starting element, and repeated elements are added using \g@addto@macro. Then, at the end of \append, \@looop is executed.

Note that tabular column specifications already provide a type of duplication/repetition using a *{<num>}{<col spec>} style, where the column specification <col spec> is repeated <num> times.


Your \append macro cannot work in the argument to tabular, where macros can be used as long as they are fully expandable; this isn't, because it contains assignments.

Here's a quick version with LaTeX3 functions. Note that this won't work in the argument of tabular if array is loaded, because this package disables expanding the argument.

However, typing l*{2}{c} as the argument seems not so complicated to need a macro.

\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\DeclareExpandableDocumentCommand{\append}{mmm}
 {
  #1\prg_replicate:nn{#3}{#2}
 }
\ExplSyntaxOff

\begin{document}

\noindent\append{c}{c}{0}

\noindent\append{cd}{c}{1}

\noindent\append{c}{c}{2}

\noindent\append{c}{c}{3}

\noindent\begin{tabular}{\append{l}{c}{2}}
1&2&3\\
\append{start}{&test}{1}\\
\append{start}{&test}{2}
\end{tabular}

\end{document}

enter image description here


The spaces are due to an extra space that you have in the definition of \append, between the opening brace and the comment. You have one more before the \else. This is how I'd write it:

\newcommand{\append}[3]{%
  % #1 = start of text, #2 = text to repeat, #3 = number of repetitions
  \ifnum #3>0
    \setcounter{tempcount}{#3}%
    \addtocounter{tempcount}{-1}%
    \append{#1#2}{#2}{\arabic{tempcount}}%
  \else
    #1%
  \fi}

The rest works, except when you try to use \append in the argument of tabular. The problem there is that \append is not expanded before the column information is needed. If you want this to work as well, I suggest that you follow @Werner's answer. It's not worth the effort re-inventing everything. However, if you must, you'll need to understand how precisely macro expansion works.