[Tex/LaTex] Color coding a text string with alternating colors

colorluatex

I was wondering if it was possible to color every second letter in a text string in LaTeX. I'm writing a report on decrypting a Vigenere cipher, and have a text string that I would like to have every alternate letter be colored differently.

So for example the string might be 'abcdefg', and I would like the output to show 'aceg' in blue and 'bdf' in red, or something like that.
Is this easily feasible in LaTeX?

Thank you guys!

Best Answer

Here's an expl3 version for alternating colours, but not for strings with whitespace (so far)

\documentclass{article}
\usepackage{xparse}

\usepackage[x11names]{xcolor}
\ExplSyntaxOn
\newcommand{\colorstring}[3]{% 
  \str_set:Nn \l_tmpa_str {#3}% store the string to a string variable
  % Now loop through the string variable and get each 'letter' 
  \int_step_inline:nnnn {1} {1} {\str_count:N \l_tmpa_str } {%
    \int_if_odd:nTF{##1}{% Is the number odd → use the first colour
      \textcolor{#1}{\str_item:Nn \l_tmpa_str {##1}}
    }{% No, use the 2nd colour
      \textcolor{#2}{\str_item:Nn \l_tmpa_str {##1}}
    }%
  }%
}
\ExplSyntaxOff

\begin{document}

\bfseries
\huge \colorstring{blue}{red}{abcdefgh}


\huge \colorstring{brown}{Green4}{ABCEDEFGH}

\end{document}

enter image description here

Another version, with alternating colours

... and providing more than two colours, as well as using in an environment. However, no empty lines are allowed! No real tests on printable characters are done so far.

\documentclass{article}
\usepackage{xparse}
\usepackage{environ}

\usepackage[x11names]{xcolor}
\ExplSyntaxOn

\NewDocumentCommand{\colorstring}{O{blue,red}+m}{%
  \clist_set:Nn \l_tmpa_clist {#1}%
  \int_zero:N \l_tmpa_int%
  \str_set:Nx \l_tmpa_str {#2}%
  \int_step_inline:nnnn {1} {1} {\str_count:N \l_tmpa_str } {%
    \str_case_x:nnF {\str_item:Nn \l_tmpa_str {##1}} {%
      {\space}{\space}
    }{%
      \int_compare:nNnTF {\l_tmpa_int } < {\clist_count:N \l_tmpa_clist } {
        \int_incr:N \l_tmpa_int
      }{%
        \int_set:Nn \l_tmpa_int {\c_one}
      }
      \textcolor{\clist_item:Nn \l_tmpa_clist {\l_tmpa_int }}{\str_item:Nn \l_tmpa_str {##1}}
    }
  }
}



\ExplSyntaxOff

\NewEnviron{ColorLettersInternal}[1]{\colorstring[#1]{\BODY}} % Internal environment for `\Body`

\NewDocumentEnvironment{ColorLetters}{O{blue,red}}{%
  \ttfamily%
  \ColorLettersInternal{#1}%
}{%
  \endColorLettersInternal%
}


\parindent=0pt
\begin{document}


\bfseries
\huge \colorstring{abcdefgh}
\huge \colorstring[brown,Green4,Aquamarine4]{ABCEDEFGH}

\colorstringnew[violet,Green4,Red4,Blue2]{TCGATGGAGGGACCAT}

\begin{ColorLetters}[Blue4,Red4,Green4,LightBlue4]
And now for something completely different
Number Three -- the Larch!
\end{ColorLetters}

\end{document}

enter image description here