John
John

Reputation: 21

String replacement in latex

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}
\newlength{\myboxh}
\settowidth{\myboxw}{\usebox{\mybox}}
\settoheight{\myboxh}{\usebox{\mybox}}
\begin{picture}(\myboxw,\myboxh)
\end{picture}

Basically I create a savebox called mybox. I insert the words "Hello World" into mybox. I create a new length/width, called myboxw/h. I then get the width/height of mybox, and store this in myboxw/h. Then I set up a picture environment whose dimensions correspond to myboxw/h. 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. Thanks.

Upvotes: 1

Views: 2976

Answers (3)

Werner
Werner

Reputation: 15055

The LaTeX kernel - latex.ltx - already provides \strip@pt, which you can use to strip away any reference to a length. Additionally, there's no need to create a length for the width and/or height of a box; \wd<box> returns the width, while \ht<box> returns the height:

\documentclass{article}

\makeatletter
\let\stripdim\strip@pt % User interface for \strip@pt
\makeatother

\begin{document}

\newsavebox{\mybox}
\savebox{\mybox}{Hello World!}

\begin{picture}(\stripdim\wd\mybox,\stripdim\ht\mybox)
  \put(0,0){Hello world}
\end{picture}

\end{document}

Upvotes: 0

Ethan Bolker
Ethan Bolker

Reputation: 217

Consider the xstring package at https://www.ctan.org/pkg/xstring.

Upvotes: 1

Alexey Malistov
Alexey Malistov

Reputation: 26975

Use the following trick:

{
\catcode`p=12 \catcode`t=12
\gdef\removedim#1pt{#1}
}

Then write:

\edef\myboxwnopt{\expandafter\removedim\the\myboxw}
\edef\myboxhnopt{\expandafter\removedim\the\myboxh}
\begin{picture}(\myboxwnopt,\myboxhnopt)
\end{picture}  

Upvotes: 1

Related Questions