使用命令多次重复另一段文字

使用命令多次重复另一段文字

我有一个名为的命令\commandone,它输出

测试。

我使用创建了它\newcommand\commandone{test}

我想要第二个命令,它接受一个整数输入,并根据输入的整数重复\commandtwo{}调用第一个命令。因此,如果,输出将变为“\commandone\commandtwo{3}

测试测试测试

答案1

\documentclass{minimal}
\usepackage{pgffor}
\newcommand{\cmd}{test}
% to provide your syntax
\newcommand{\Repeat}[2]{% \repeat already defined
    \foreach \n in {1,...,#1}{#2}
}
\begin{document}
\foreach \n in {1,...,4}{\cmd}

\Repeat{6}{\cmd}
\end{document}

在此处输入图片描述

答案2

看看 David Kastrup 的\replicate宏:

http://www.gust.org.pl/projects/pearls/2005p/david-kastrup/bachotex2005-david-kastrup-pearl3.pdf

\documentclass{article}
\newcommand\replicate[2]{%
  \ifnum#1>0 #2%
    \expandafter\replicate\expandafter{\number\numexpr#1-1}{#2}%
  \fi
}%
\newcommand\commandone{test}
\newcommand\commandtwo[1]{\replicate{#1}{\commandone}}

\begin{document}

\commandone

\commandtwo{3}%

\end{document}

在此处输入图片描述

\replicate这里有这样一个变体,在任何情况下,在/\commandtwo击中两次后你都会得到结果\expandafter

\documentclass{article}
\newcommand\UDfirstoftwo[2]{#1}
\newcommand\UDsecondoftwo[2]{#2}

\newcommand\replicate[2]{%
  \romannumeral0\replicateb{#1}{#2}{}%
}%

\newcommand\replicateb[3]{%
  \ifnum#1>0 \expandafter\UDfirstoftwo\else\expandafter\UDsecondoftwo\fi
  {\expandafter\replicateb\expandafter{\number\numexpr#1-1}{#2}{#3#2}}%
  { #3}%
}%
\newcommand\commandone{test}
\newcommand\commandtwo[1]{%
  \romannumeral\expandafter\UDsecondoftwo\replicate{#1}{\commandone}%
}

\begin{document}

\commandone

\commandtwo{3}%

\expandafter\expandafter\expandafter\def
\expandafter\expandafter\expandafter\test
\expandafter\expandafter\expandafter{\replicate{4}{\commandone}}

\texttt{\meaning\test}

\expandafter\expandafter\expandafter\def
\expandafter\expandafter\expandafter\testb
\expandafter\expandafter\expandafter{\commandtwo{5}}

\texttt{\meaning\testb}


\end{document}

在此处输入图片描述

这是一个没有使用 ϵ-TeX-extensions/without 的变体\numexpr

\documentclass{article}
\newcommand\UDfirstoftwo[2]{#1}
\newcommand\UDsecondoftwo[2]{#2}

\newcommand\replicate[1]{%
  \romannumeral0\expandafter\replicateA
                \expandafter{\romannumeral\number\number#1 000}%
}%
\newcommand\replicateA[2]{\replicateB{#2}{}#1\relax}
\newcommand\replicateB[3]{%
  \if#3m\expandafter\UDfirstoftwo\else\expandafter\UDsecondoftwo\fi
  {\replicateB{#1}{#2#1}}{ #2}%
}%


\newcommand\commandone{test}
\newcommand\commandtwo[1]{%
  \romannumeral\expandafter\UDsecondoftwo\replicate{#1}{\commandone}%
}

\begin{document}

\commandone

\commandtwo{3}%

\expandafter\expandafter\expandafter\def
\expandafter\expandafter\expandafter\test
\expandafter\expandafter\expandafter{\replicate{4}{\commandone}}

\texttt{\meaning\test}

\expandafter\expandafter\expandafter\def
\expandafter\expandafter\expandafter\testb
\expandafter\expandafter\expandafter{\commandtwo{5}}

\texttt{\meaning\testb}


\end{document}

在此处输入图片描述

相关内容