[Tex/LaTex] Replace character defined by ASCII code (by something else)

catcodes

I am trying to replace, in a given string, some characters. The characters to be replaced is given by its ASCII code. So for example, in abc, I want to replace character 97 (which is a, but I don't know this yet) by something else, let's say a dot (.).

Now, a, \char97 and \char\thenumber all look the same to me when printing them in a document, but replacing this respective argument in a string a only works with the first. Why is that, and how can I solve it? This is my MWE (unchanged from the original question):

\documentclass{book}
\usepackage{xstring}
\newcounter{number}
\setcounter{number}{97}
\newcommand{\replace}[1]{\StrSubstitute{#1}{a}{.}}
\begin{document}
a

\char97

\char\thenumber

\replace{a}

\expandafter\replace{\char97}

\expandafter\expandafter\expandafter\replace{\char\thenumber}

\end{document}

Best Answer

There is a standard \lowercase trick which creates a token with a given ASCII code. For example you need to replace all ASCII 97 characters from the string abcabcac by double ?. Then you can try:

\bgroup\lccode`X=97 \lowercase{\egroup \StrSubstitute{abcabcabc}{X}{??}}
output:  ??bc??bc??bc

This code creates the token with given ASCII code instead the X letter and then the \StrSubstitute macro is executed.

Of course, your processed string cannot include the X letter itself. If this is a problem then you can create the following \replace macro:

\def\replace#1{\bgroup \lccode`X=#1 \lowercase{\egroup \replaceA{X}}{abcabcabcXuv}}
\def\replaceA#1#2{\StrSubstitute{#2}{#1}{??}}

\replace{97}
output:  ??bc??bc??bcXuv
\replace{98}
output:  a??ca??ca??cXuv
Related Question