SalysBruoga - 1 year ago 112
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?

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}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download