1

How can I make a command (or is there an existing one?) which takes two arguments: 1) character type 2) N (count) and puts N number of characters side by side?

\newcommand{\foo}[2]
{
    % sample: \foo{c}{3} -> ccc
}
Shibli
  • 452

1 Answers1

1
\newcommand{\stringnumber}[2]{%
    \ifnum #2>0
        #1%
        \stringnumber{#1}{\numexpr#2-1}
    \fi
}

The previous code, when the number of requested repetitions is high, generates very long token lists. Here's a better implementation that avoids the problem.

\documentclass{article}

% it's better if the number of repetitions is first
\newcommand{\stringnumber}[2]{\dostringnumber{#2}{#1}}
\makeatletter
% call \dostringnumber recursively
\newcommand{\dostringnumber}[2]{%
  \ifnum #1>0
    % produce the second argument
    #2%
    % generate the next call; the last \expandafter gets rid of \else
    \expandafter\dostringnumber\expandafter{\number\numexpr#1-1\expandafter}%
  \else
    % get rid of the text in case we are at the end of the recursion
    \expandafter\@gobble
  \fi
  {#2}%
}
\makeatother

\begin{document}

X\stringnumber{Ok!}{7}X\stringnumber{Ok!}{1}X\stringnumber{Ok!}{0}X

\end{document}
RicoRally
  • 1,252
  • I hope you don't mind for the remarks I added. – egreg Nov 12 '14 at 17:32
  • I don't, in my own interest I prefer when better content is shown. So thank you. – RicoRally Nov 13 '14 at 07:54
  • @egreg BTW why did you put a \number there? – RicoRally Nov 13 '14 at 08:15
  • 1
    This expands \numexpr#1-1 to an explicit number and also has the effect of triggering \expandafter which gets rid of \else up to and including \fi. So the next \dostringnumber is executed outside any conditional. The problems with your code are that a -1 is added for each iteration and conditionals heap up. – egreg Nov 13 '14 at 08:30