Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

store a text string in latex and then add other text to it (concatenate)

Tags:

string

latex

I start by defining a command to store the string "Hello":

\newcommand{\textstring}{Hello}

I would like to append the string " world" but unfortunately this code causes an error:

\renewcommand{\textstring}{\textstring world}
like image 401
flaflamm Avatar asked Jun 27 '10 01:06

flaflamm


3 Answers

Similar to David Underhill's answer is the following

\newcommand{\textstring}{Hello}
\makeatletter
\g@addto@macro\textstring{ world}
\makeatother

The g@addto@macro macro achieves the same effect, and may produce slightly more readable code (especially if your code is in a package/style, or if you're already in a \makeatletter & \makeatother situation)

like image 87
drfrogsplat Avatar answered Sep 20 '22 20:09

drfrogsplat


Used the input from this question to generate

\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

(sorry brian, but this was the most illustrative example I could think of)

The scructure can help you create a simple todo list with something like:

\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

Hope this can help someone out there trying to concat strings for this purpose.

like image 42
Neon Avatar answered Sep 18 '22 20:09

Neon


You can accomplish this by using \expandafter. For example:

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

If you don't use \expandafter then you end up with a recursion problem. You can read more about it here.

like image 28
David Underhill Avatar answered Sep 21 '22 20:09

David Underhill