Text FormattingConcatenating strings

Information and discussion about LaTeX's general text formatting features (e.g. bold, italic, enumerations, ...)
Post Reply
theo moore
Posts: 72
Joined: Thu Jan 15, 2009 3:16 pm

Concatenating strings

Post by theo moore »

This is a simple question which, after some time googling I have yet to find an answer: How do you concatenate a string in LaTeX? For example, I wish to write a command that reads in files file1_a.dat, where '1' and 'a' are inputs. So I want something like,

Code: Select all

\newcommand{\readme}[2]{%
 \input{['file', #1, '_', #2, '.dat']}
}
where I've used Matlab notation for combining strings and I would call \readme{a, b}. How is it done in Latex?

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org
LaTeX Beginner's Guide LaTeX Cookbook LaTeX TikZ graphics TikZによるLaTeXグラフィックス
josephwright
Site Moderator
Posts: 814
Joined: Tue Jul 01, 2008 2:19 pm

Concatenating strings

Post by josephwright »

Code: Select all

\newcommand\reame[2]{%
  \input{#1_#2.dat}%
}
(I'm assuming you've dealt properly with the filenames here: underscores tend to be bad news!)
Joseph Wright
theo moore
Posts: 72
Joined: Thu Jan 15, 2009 3:16 pm

Concatenating strings

Post by theo moore »

josephwright wrote:

Code: Select all

\newcommand\reame[2]{%
  \input{#1_#2.dat}%
}
(I'm assuming you've dealt properly with the filenames here: underscores tend to be bad news!)
Just out curiosity, what if you had the actual string '#1' as a file name? For example, my file would actually be named file#1.dat

How would you protect the portion '#1' from being replaced by the input?
phi
Posts: 577
Joined: Tue Oct 21, 2008 8:10 pm

Concatenating strings

Post by phi »

In that case you have to convert the # into something harmless:

Code: Select all

\edef\x{file\string#1.dat}
\input{\x}
Post Reply