[Tex/LaTex] Extract first & last characters of macro argument


In LaTeX, how do I extract/isolate/determine the first and last characters of a macro argument?

Specifically, in the case I'm dealing with, the argument happens to be a base-10 integer (call it N). One way I can think of for the rightmost digit is to compute N mod 10, and for the leftmost digit to repeatedly divide by 10—except I haven't attempted anything like that yet and I don't know how reasonable that is or even if that is possible in (La)TeX. Extracting the characters as string entities would be fine too; I have no requirement of producing numeric values. (Edit: I forgot to mention earlier that I would prefer the solution to work for arbitrarily large numeric values—or at least up to, say, 7 or 10 digits—which might necessitate a string-base solution rather than a numeric solution.)

Ultimately, I just need the isolated characters in a form that I can compare using if/then constructs, e.g.:

  (something to extract rightmost digit of #1)
  (something to extract leftmost digit of #2)
  \ifthenelse{\rightmost\equal 2}{\kern.02em}{}%
  \ifthenelse{\rightmost\equal 4}{\kern.03em}{}%
  \ifthenelse{\rightmost\equal 7}{\kern-.02em}{}%
  \ifthenelse{\leftmost\equal 1}{\kern.02em}{}%
  \ifthenelse{\leftmost\equal 4}{\kern-.03em}{}%
  \ifthenelse{\leftmost\equal 5}{\kern.03em}{}%
  \ifthenelse{\leftmost\equal 7}{\kern.03em}{}%

Additional background: This is for fine-tuning the kerning in the numerator and denominator of fractions (related question Improving kerning in fractions).

Best Answer

You could use the xstring package



    First letter: \firstletter

    Last letter: \lastletter


I’m a little busy so please excuse that I didn’t build it in you MWE ;-)