SalysBruoga SalysBruoga - 1 month ago 14
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

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

2
4

\documentclass{article}

\usepackage{xparse}

\ExplSyntaxOn
% \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 }
}
\ExplSyntaxOff

\begin{document}

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

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

\end{document}
Comments