[Tex/LaTex] String replacement in LaTeX

diagramslengthsstrings

I'd like to know how to replace parts of a string in LaTeX. Specifically I'm given a measurement (like 3pt, 10mm, etc) and I'd like to remove the units of that measurement (so 3pt–>3, 10mm–>10, etc). The reason why I'd like a command to do this is in the following piece of code:

\newsavebox{\mybox}
\sbox{\mybox}{Hello World!}
\newlength{\myboxw}
\settowidth{\myboxw}{\usebox{\mybox}}
\begin{picture}(\myboxw,\myboxw)
\end{picture}

Basically I create a savebox called mybox. I insert the words "Hello World" into mybox. I create a new length, called myboxw. I then get the width of mybox, and store this in myboxw. Then I set up a square picture environment whose dimensions correspond to myboxw. The trouble is that myboxw is returning something of the form "132.56pt", while the input to the picture environment has to be dimensionless: \begin{picture}{132.56, 132.56}.

So, I need a command which will strip the units of measurement from a string.

Best Answer

The internal LaTeX macro \strip@pt returns a length in pt without the unit. For example, if you set \myboxw to 10 mm, it will have a length of 28.45274 pt, and this code

\makeatletter
\strip@pt\myboxw
\makeatother

will output just 28.45274. So you could use this or define your own command like:

\makeatletter
\newcommand*{\stripunit}[1]{\strip@pt#1}
\makeatother

\strip@pt uses \the on a dimen register and strips pt, that's why you did not get 10 (mm) but the corresponding value in pt without unit. Such a conversion to pt and stripping pt seems better to me than just doing string replacement getting some value without knowing the unit.

You can see the source code of \strip@pt with comment if you look into source2e.pdf in section 26.1 Macros for the user (part of the section 26. Selecting a new font), you could open it at the command prompt by typing texdoc source2e or get it from CTAN.