[Tex/LaTex] In LaTeX, make a box with the width of another text

boxeshorizontal alignmentwidth

I am looking for a command like \makebox{text to set width}[c]{new text} which would make a box with the width of text to set width containing ____new text____ centered.

Best Answer

Something like this?

\documentclass{article}
\newlength\stextwidth
\newcommand\makesamewidth[3][c]{%
  \settowidth{\stextwidth}{#2}%
  \makebox[\stextwidth][#1]{#3}%
}
\begin{document}
  \fbox{\makesamewidth[c]{text to set width}{new text}}
\end{document}

matched width

If the order of arguments is important you can use xparse:

\documentclass{article}
\usepackage{xparse}
\newlength\stextwidth
\NewDocumentCommand\makesamewidth{ m O{c} m }{%
  \settowidth{\stextwidth}{#1}%
  \makebox[\stextwidth][#2]{#3}%
}
\begin{document}
  \fbox{\makesamewidth{text to set width}[c]{new text}}
\end{document}

using \NewDocumentCommand rather than \newcommand.