在 LaTeX 中存储一个文本字符串,然后添加其他文本(连接)。

12

我首先定义一个命令来存储字符串 "Hello":

\newcommand{\textstring}{Hello}

我想要在字符串后面添加 "world" 但是不幸的是这段代码会导致错误:

\renewcommand{\textstring}{\textstring world}
4个回答

12

您可以使用\expandafter来实现此目的。例如:

% redefine \textstring by appending " world" to it
\expandafter\def\expandafter\textstring\expandafter{\textstring { }world}

如果你不使用\expandafter,那么你最终会遇到递归问题。你可以在这里阅读更多相关信息。


这个方法很好用(即使附加的文本包含命令)。但是现在我遇到了另一个问题:当我在文本中使用\textstring时,它显示“Hello world”,但我必须在\endnotetext[\value{enumi}]{\textstring}中使用它,这会生成一个空的尾注。 - flaflamm

4
类似于David Underhill的回答,以下是相似的方法。
\newcommand{\textstring}{Hello}
\makeatletter
\g@addto@macro\textstring{ world}
\makeatother
g@addto@macro宏可以达到相同的效果,并且可能会产生更易读的代码(特别是如果你的代码在一个包/样式中,或者如果你已经处于\makeatletter\makeatother的情况下)。

3

使用此问题的输入生成

\edef\history{ }
\newcommand{\historyAdd}[1]{\edef\history{\history{}#1 }}
\newcommand{\historyAddEcho}[1]{#1\historyAdd{#1}}

The history was: 
\historyAddEcho{Hi brian}
\historyAdd{you idiot}
\historyAddEcho{how are you?}

\lipsum[3]

The real history was: \history

抱歉 Brian,但这是我能想到的最具说明性的例子。

使用该结构,您可以创建一个简单的待办事项列表,例如:

\lipsum[1]

\historyAdd{\\work more with: }
\section{\historyAddEcho{Introduction}}

\lipsum[1]

\historyAdd{\\work more with the text on page \thepage}
\lipsum[1]

\section{ToDo:}
\history

希望这篇文章能帮助那些尝试拼接字符串的人。

3
问题在于这会覆盖 \textstring 的定义,而不是引用旧的定义。为了追加,标准的方式是使用 TeX 命令 \edef,它在分配之前展开定义。因此,如果你有:
\def\textstring{Hello} % Or with \newcommand
\edef\textstring{\textstring{} world}

LaTeX 将改变 \edef 的右侧为 Hello world,然后重新分配给 \textstring,这就是您想要的。 相反,在您当前的版本中,\newcommand 不会扩展右侧,因此当您使用 \textstring 时,它会扩展为 \textstring world,其本身又扩展为 \textstring world world,一直扩展下去……你知道的。


当要添加的文本包含命令时,这种方法似乎存在问题,会生成许多错误。 - flaflamm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接