The crux of the answer is given in How to define a macro to create a new macro with a name passed as its argument? with the #1aux
macro requiring additional \csname
s and associated \expandafter
s to ensure the \csname
happens first.
\newcommand{\newspace}[2]{%
\expandafter\newlength\expandafter{\csname#1aux\endcsname}%
\expandafter\settowidth\expandafter{\csname#1aux\endcsname}{#2}%
\expandafter\newcommand\expandafter{\csname#1\endcsname}{%
\expandafter\hspace\expandafter*\expandafter{\csname#1aux\endcsname}}}
However with the aid of the calc
package, \widthof
circumvents a lot of unpleasant boilerplate code
\newcommand{\betternewspace}[2]{%
\expandafter\newcommand\expandafter{\csname#1\endcsname}{\hspace*{\widthof{#2}}}}
\hphantom{#2}
(which doesn't require calc
) has a similar effect to \hspace*{\widthof{#2}}
but acts as \hspace
rather than \hspace*
.
\documentclass{article}
\usepackage{calc}
\newcommand{\newspace}[2]{%
\expandafter\newlength\expandafter{\csname#1aux\endcsname}%
\expandafter\settowidth\expandafter{\csname#1aux\endcsname}{#2}%
\expandafter\newcommand\expandafter{\csname#1\endcsname}{\expandafter\hspace\expandafter*\expandafter{\csname#1aux\endcsname}}}
\newcommand{\betternewspace}[2]{%
\expandafter\newcommand\expandafter{\csname#1\endcsname}{\hspace*{\widthof{#2}}}}
\begin{document}
\newspace{QQspace}{QQ}
\betternewspace{QQspaceTwo}{QQ}
\noindent%
AQQA\\
A\QQspace B\\
A\QQspaceTwo B\\
\end{document}
