Having fun with strings, I found three different macros to loop over a string character by character. However, I am not very sure how they work exactly. Can somebody explain the mechanism of each of them? Which is the most "correct" one? Is there some other way to construct this macro?
I have changed the original ones so that they all look as similar as possible.
Macro based on one by Tarass:
This is the easiest one to understand for me.
Since the arguments are delimited, the first one is the first letter and the rest is reintroduced into the loop.
The looping works from within the \if
statement.
Macro based on one by David Carlisle:
This one is trickier.
The looping comes from inside the \if
statement, but not really.
If the \expandafter
is eliminated, it does not work.
If the \xloop
is placed behind the \fi
it does not work either.
So what is happening exactly?
The rest is easier, every time \xloop
is executed, it finds the remaining part of the string and takes the first character.
Macro based on one by Florent:
This one is still more complicated (for me, at least).
The looping works from outside the \if
statement, but the characters are accessed one by one as before.
Surprisingly, here the spaces are not discarded.
This can be achieved also in the previous macros with \obeyspaces
.
\documentclass{article}
\begin{document}
\subsection*{Macro based on one by Tarass:}
\def\xloop<#1#2>{%
\ifx\relax#1
\else
(#1)\xloop<#2>%
\fi}
\def\markletters#1{\xloop<#1\relax>}
\markletters{Hello World!}
\subsection*{Macro based on one by David Carlisle:}
\def\xloop#1{%
\ifx\relax#1
\else
(#1)\expandafter\xloop%
\fi}
\def\markletters#1{\xloop#1\relax}%
\markletters{Hello World!}
\subsection*{Macro based on one by Florent:}
\def\gobblechar{\let\xchar= }
\def\assignthencheck{\afterassignment\xloop\gobblechar}
\def\xloop{%
\ifx\relax\xchar
\let\next=\relax
\else
(\xchar)\let\next=\assignthencheck
\fi
\next}
\def\markletters#1{\assignthencheck#1\relax}
\markletters{Hello World!}
\end{document}