SalysBruoga SalysBruoga - 1 year ago 101
LaTeX Question

LaTeX count number of occurrences of a character in a string

Let's say I have some string

This~is a ~test
. I need to count the number of
characters. Is there some way to do this in LaTeX?

Answer Source

Using expl3 you can split the token list into items and then count the items (less 1):




% \CountSubStr{<substring>}{<string>}
\NewDocumentCommand{\CountSubStr}{ m m }{
  \seq_set_split:Nnn \l_tmpa_seq { #1 } { #2 }
  \fp_to_int:n {(\seq_count:N \l_tmpa_seq) - 1 }


\CountSubStr{~}{This~is a ~test}% 2

\CountSubStr{yes}{a yes b yes c yes deyesfg yehs ij}% 4