# TeX, LaTeX capabilities in counting occurrences in text of chars defined in a given list

I am asking this question in part because I am not completely aware of TeX, LaTeX capabilities. Imagine that I want to count the number occurrences of charecters defined in a certain list. The usage would be as follows:

``````\charlist{123}
or
\charlist{1,2,3}

\startcountchar
123 456

\printcountchar -> 3
\stopcountchar
\printcountchar -> 0
``````

The problem here is how to set up the `\charlist` list and define the `\startcountchar`. I know that somewhere a counter must be defined, that will be updated with `\refstepcounter` each time a char is fount that is in the `\charlist`. But how can I compare each char that will be in the text with the ones defined in the list (if easier, and maybe better, commas or other separator can be used to define the `\charlist`).

The command `\stopcount` shall stop the counting process, which could simply be reset the value of the counter. The `\printcountchar` would be used to display the current value of the counter. Of course, a `\printcountchar` right after a `\stopcountchar` would give a zero.

Additionally (as a future enhcement), some error checking could also be done, e.g., use `\startcountchar`, `\printcountchar`, `\stopcountchar` without the `\charlist` definition; Use `\printcountchar`, `\stopcountchar` without a `\startcountchar` at begining; two or more `\startcount` would be the same as just one, etc. Further improvements could be define different lists of chars, and expand the above commands to have additional argument like `[name=<char list name>]`.

Any start will be welcome.

-
–  Andrew Swann Apr 29 at 14:06
The bigger problem here is collecting up the input: are we allowed to for example use the `environ` package? Do you want to typeset the 'counted' content, or just do the counting? –  Joseph Wright May 4 at 21:18
@JosephWright an environment can be used if required. An approach is already here: tex.stackexchange.com/questions/108029/count-chars-with-xstring. But of course it can be enhanced. –  cacamailg May 4 at 23:14
The `stringstrings` package can extract information from strings. For example, `\findchars{string}{match-char}` finds number of occurances of match-char. The command `\whereischar{string}{match-char}` tells you where match-char first occurs in string. There are also string extraction macros for grabbing parts of the input string. If you are a bit more specific on what manipulations/extractions you need, I could try something. –  Steven B. Segletes May 17 at 18:05
@StevenB.Segletes at time, I was interesting in counting the number of characters inside an environment. See my previous comment, where I defined the list of characters to be considered (actually it was the whole alphabet). I was interested in this because I had to submit a manuscript and each section had a fixed number of characters. –  cacamailg May 17 at 19:49
show 1 more comment