Is there a reverse \alph?
The backtick in numerical context can be used to get the character code of a letter. This can be used to calculate the position of the letter in the alphabet.
The definition range for the argument of
\inversalph
isa
toz
andA
toZ
for\inverseAlph
.The letter can be hidden inside a macro (or even nested macros).
\documentclass{article}
\newcommand*{\inversalph}[1]{%
\the\numexpr(\expandafter`\romannumeral-`\x#1-`a+1)\relax
}
\newcommand*{\inversAlph}[1]{%
\the\numexpr(\expandafter`\romannumeral-`\x#1-`A+1)\relax
}
\begin{document}
a: \inversalph{a},
b: \inversalph{b},
k: \inversalph{k},
z: \inversalph{z}
A: \inversAlph{A},
B: \inversAlph{B},
K: \inversAlph{K},
Z: \inversAlph{Z}
\def\lettera{a}
\def\letterz{z}
\def\letteraa{\lettera}
\def\letterzz{\letterz}
\lettera: \inversalph{\lettera} = \inversalph{\letteraa},
\letterz: \inversalph{\letterz} = \inversalph{\letterzz}
Page: \inversalph{\alph{page}}
\end{document}
Remarks:
\numexpr
is used for the calculations.\romannumeral-`\x
is a trick to expand the following token multiple times.
A quick solution with \int_from_alph:n
or \int_from_roman:n
from expl3
. Note that a
and A
does not matter here, as well as uppercase and lowercase roman figures are identical here.
The \setcounter{section}{\alphtonumber{w}}
example was used to show that the macros are expandable.
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\newcommand{\alphtonumber}[1]{%
\int_from_alph:n{#1}
}
\newcommand{\romantonumber}[1]{%
\int_from_roman:n{#1}
}
\ExplSyntaxOff
\usepackage{pgffor}
\begin{document}
\alphtonumber{a} -- \alphtonumber{z}
And \alphtonumber{M}\ is a pretty number and \romantonumber{MMXVI} is a good year (more or less), as well as \romantonumber{mdcccclxxiv} was a good year.
\setcounter{section}{\alphtonumber{w}}
\section{Foo}
\end{document}
The number is always stored in the counter while \alph
and the like are only for displaying the value.
For example if you define
\newcounter{foo}
\renewcommand{\thefoo}{\alph{foo}}
with
\thefoo
you get a, b, c, …
but with
\value{foo}
you can always access the integer value of the counter.