# Applying Macro to xth Symbol of String

I would like to define a command that puts a sequence of symbols above the xth symbol of another sequence of symbols.

It seems nicer without a separator, but for higher usability a separator may be necessary. I am not sure.

That means, in the example below the command \putAbove should be redefined to produce the output shown behind becomes.

The questions seems to be related to e.g. this, but I am not able to put it into use here.

\documentclass{article}
\usepackage{amsmath}
\newcommand{\putAbove}[3]{\backslash putAbove\{#1\}\{#2\}\{#3\}}
\begin{document}
$\putAbove{q_0}{1}{||\phi}$ becomes $\overset{q_0}||\phi$

$\putAbove{q}{1}{||\phi}$ becomes $\overset{q}||\phi$

$\putAbove{q}{3}{|||}$ becomes $||\overset{q}|$
\end{document}


\documentclass{article}
\usepackage{amsmath}
\newcommand{\putAbove}[3]{\xputAbove{#1}{#2}#3}
\newcommand\xputAbove[2]{\ifnum#2=1 \expandafter\xxputAbove\else\expandafter\xxxputAbove\fi{#1}{#2}}
\newcommand\xxputAbove[3]{\overset{#1}{#3}}
\newcommand\xxxputAbove[3]{#3\xputAbove{#1}{\numexpr(#2)-1\relax}}

\begin{document}

$\putAbove{q_0}{1}{||\phi}$ becomes $\overset{q_0}||\phi$

$\putAbove{q}{1}{||\phi}$ becomes $\overset{q}||\phi$

$\putAbove{q}{3}{|||}$ becomes $||\overset{q}|$
\end{document}


The implementation here is just an iteration based in the observation that

\putAbove{q}{1}{abc}


is

\putAbove{q}{1}a bc


which is

\overset{q}{a} bc


and

\putAbove{q}{n}abcde


is

a\putAbove{q}{n-1}bcde

• That is great, thank you! Is it possible that you add a little explanation? Nov 24, 2017 at 21:28
• @HeinrichOdy added some notes Nov 24, 2017 at 21:39

An expl3 implementation. With \tl_range_braced:nnn { <tokens> } { x } { y } you get the items from place x to place y inclusive. Note that arithmetic is allowed in the second and third argument. Similarly, \tl_item:nn { <tokens> } { x } returns the x-th item.

\documentclass{article}
\usepackage{amsmath}
\usepackage{xparse}

\ExplSyntaxOn

\NewDocumentCommand{\putAbove}{mmm}
{% #1 = symbol to put above, #2 = position, #3 = symbols
\tl_range_braced:nnn { #3 } { 1 } { #2 - 1 }
\overset{ #1 } { \tl_item:nn { #3 } { #2 } }
\tl_range_braced:nnn { #3 } { #2 + 1 } { \tl_count:n { #3 } }
}

\ExplSyntaxOff

\begin{document}

$\putAbove{q_0}{1}{||\phi}$ becomes $\overset{q_0}||\phi$

\medskip

$\putAbove{q}{1}{||\phi}$ becomes $\overset{q}||\phi$

\medskip

$\putAbove{q}{3}{|||}$ becomes $||\overset{q}|$

\end{document}


• This looks nicely understandable. But it does not compile for me when I use \putAbove. With only the declaration of the command it compiles, though. Any ideas perhaps? Nov 24, 2017 at 21:40
• @HeinrichOdy Most likely you need to update your TeX distribution. Nov 24, 2017 at 21:57