Latest update

# String operation creates error in pgfmathsetmacro

2018-10-10 05:45:34

I am trying to reference the first character of a string within a pgfmathsetmacro, however, the macro \StrLeft from xstring, I believe, is not playing well with pgfmathsetmacro.

Take the following example that replicates this problem:

\documentclass{article}

\usepackage{tikz}

\usepackage{xstring}

\begin{document}

\begin{tikzpicture}

\newcommand{\str}{hello};

\newcommand{\firstChar}

{

\StrLeft{\str}{1}

};

\pgfmathsetmacro{\halfStr}{width("\str") * 1pt / 2cm};

\pgfmathsetmacro{\halfFirstChar}{width("\firstChar") * 1pt / 2cm};

\node at (0, 0) {\str};

\draw [color=black] (\halfFirstChar - \halfStr, 0cm) -- (\halfFirstChar - \halfStr,-1cm);

\end{tikzpicture}

\end{document}

The following code should output the following:

(The string "hello" printed, along with a vertical line beginning from the halfway point of the "h" character and then moving downwards 1 centime

• This is a bit tricky because of expansion issues. The perhaps easiest way to make it work is to use the optional argument of \StrLeft to define \firstChar. Then the rest works as it should, I think.

\documentclass{article}

\usepackage{tikz}

\usepackage{xstring}

\begin{document}

\begin{tikzpicture}

\newcommand{\str}{hello}

\StrLeft{\str}{1}[\firstChar]

\pgfmathsetmacro{\halfStr}{width("\str") * 1pt / 2cm};

\pgfmathsetmacro{\halfFirstChar}{width("\firstChar") * 1pt / 2cm};

\node at (0, 0) {\str};

\draw [color=black] (\halfFirstChar - \halfStr, 0cm) -- (\halfFirstChar - \halfStr,-1cm);

\end{tikzpicture}

\end{document}

I believe to also sense where the journey may go. You need to be a bit careful since nodes have outer and inner seps, which may affect the position, but you can set those to 0. And actually you do not need the \pgfmathsemacro thingy, the TikZ parser is very versatile, it even understands pts:

\documentclass{article}

\usepackage{tikz}

\usepa

2018-10-10 07:22:49