[Tex/LaTex] Next subsequent letter in the alphabet

alphabet

Getting the next letter of the alphabet is no problem in most programming languages I know. However, in LaTeX, it doesn't seem to be that trivial.

I have looked at how to make 26 macros (here at stackoverflow) but that question and its answers does not involve manipulations of the underlying unicode or something like that.

It is fine if the boundary case (e.g. the lowercase “z”) is not handled at all. I was thinking myself of something like the following:

\mydefalphabet abcdefghijklmnopqrstuvwxyz \mydefalphabet
\mydefalphabetshifted bcdefghijklmnopqrstuvwxyza \mydefalphabetshifted

Can I return in this case the symbol at the shifted range when given the nonshifted range perhaps?

The envisioned command would be:

\newcommand\nextletter[1]{ 
}

And used as $\nextletter{i}$ in math mode. I can then use $\robotindex$ (equal to i) and $\other{\robotindex}$ in my formulas (with other equivalent to nextletter).

Best Answer

Approach 1

This works for miniscule letters in the a-z range and has an optional argument (the shifting amount).

Code

\documentclass{article}
\newcommand*{\nextLetter}[2][1]{%
    \edef\numLet{\expandafter\number\expandafter`#2}%
    \edef\numNewLet{\number\numexpr\numLet+#1\relax}%
    \ifnum\numNewLet>122\relax%
        \edef\numNewLet{\number\numexpr\numNewLet-26\relax}%
    \fi%
    \expandafter\char\expandafter\numNewLet%
}
\def\robotindex{i}
\begin{document}
\nextLetter{a}%           a => b
\nextLetter{z}%           z => a
\nextLetter[13]{a}%       a => n
\nextLetter{\robotindex}% i => j
\end{document}

Approach 2

This approach uses the macros \myAlphabet and \myAlphabetShifted to look for the “next” letter.

Code

\documentclass{article}
\usepackage{xstring}
\def\myAlphabet{abcdefghijklmnopqrstuvwxyz}
\def\myAlphabetShifted{bcdefghijklmnopqrstuvwxyza}
\newcommand*{\nextLetter}[1]{%
    \StrPosition{\myAlphabet}{#1}[\myPosition]%
    \StrChar{\myAlphabetShifted}{\myPosition}%
}
\def\robotindex{i}
\begin{document}
\nextLetter{a}%           a => b
\nextLetter{z}%           z => a
\nextLetter{a}%           a => b
\nextLetter{\robotindex}% i => j
\end{document}
Related Question