制作字符串的命令

制作字符串的命令

我如何创建一条命令(或者是否存在一条现有的命令?)它接受两个参数:1)字符类型 2)N(计数)并将 N 个字符并排放置?

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

答案1

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

当请求的重复次数很高时,上面的代码会生成非常长的标记列表。这里有一个更好的实现,可以避免这个问题。

\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}

相关内容