Apply command on nth character of a word

Assuming "character" means "a single character token in input" (so just ASCII with pdftex but Unicode input with xetex or luatex) then

\documentclass{article}
\usepackage{xcolor}

\begin{document}

\makeatletter
\def\ColorNthChar#1#2{\xColorNthChar{#1}#2\@empty}
\def\xColorNthChar#1#2{\ifnum\ifx\@empty#21\else#1\fi=1 \textcolor{red}{#2}\expandafter\@gobbletwo
    \else#2\fi\xColorNthChar{\numexpr#1-1\relax}}
\makeatother
% example of use 

\ColorNthChar{3}{classification}  \ColorNthChar{23}{examination}  \ColorNthChar{8}{examination}

\end{document}

updated version that checks if the word is too short.


A simple implementation in expl3:

\documentclass{article}

\usepackage{xparse,xcolor}

\ExplSyntaxOn

\NewDocumentCommand{\colornth}{O{red}mm}
 {% #1 = color to use, #2 = position, #3 = word
  % deliver all characters before the chosen position
  \tl_range:nnn { #3 } { 1 } { #2 - 1 }
  % deliver the character in the chosen position with the desired color
  \textcolor{#1}{ \tl_item:nn { #3 } { #2 } }
  % deliver all characters after the chosen position
  \tl_range:nnn { #3 } { #2 + 1 } { -1 }
 }

\ExplSyntaxOff

\begin{document}

\colornth{3}{examination}

\colornth[blue]{-3}{examination}

\end{document}

With negative numbers you start counting from the end.

enter image description here

Just for fun, how to color differently several characters.

\documentclass{article}

\usepackage{xparse,xcolor}

\ExplSyntaxOn

\NewDocumentCommand{\colornth}{O{red}mm}
 {% #1 = color to use, #2 = number, #3 = word
  \tl_range:nnn { #3 } { 1 } { #2 - 1 }
  \textcolor{#1}{ \tl_item:nn { #3 } { #2 } }
  \tl_range:nnn { #3 } { #2 + 1 } { -1 }
 }
\NewDocumentCommand{\colorsome}{mm}
 {% #1 = list of chars to color, #2 = word
  % split the given token list
  \seq_set_split:Nnn \l_tmpa_seq { } { #2 }
  % with \seq_indexed_map_inline:Nn we have ##1=item number, ##2=item
  \seq_indexed_map_inline:Nn \l_tmpa_seq
   {
    \textcolor{ \int_case:nnF { ##1 } { #1 } { . } }{ ##2 }
   }
 }

\ExplSyntaxOff

\begin{document}

\colornth{3}{examination}

\colornth[blue]{-3}{examination}

\colorsome{{3}{red}{6}{blue!75!red}}{examination}

\end{document}

The first argument to \colorsome should be a list of pairs {number}{color}; since \int_case:nnF is fully expandable, at the end we will get either the color for a chosen position, or . which denotes the current color.

enter image description here


\documentclass{article}
\usepackage{xcolor,xparse}

\begin{document}
\ExplSyntaxOn
\NewDocumentCommand\ColorNthChar {mm}
{ \int_zero:N\l_tmpa_int
  \tl_map_inline:nn
   {
    #2
   }
   {
    \int_incr:N\l_tmpa_int
    \int_compare:nNnTF {\l_tmpa_int}={#1}
     {
       \textcolor{red}{##1}
     }
     {
       ##1
     }
   }
}
\ExplSyntaxOff    
% example of use

% example of use

\ColorNthChar{3}{examination}
\ColorNthChar{23}{examination}
\ColorNthChar{8}{examination}

\end{document}

enter image description here

Tags:

Macros