LeetCode 434. Number of Segments in a String (LaTeX)

Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.

Example

Example 1:

Input: "Hello, my name is John"
Output: 5

Notes

Please note that the string does not contain any non-printable characters.

Solution

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{amsmath}
\usepackage{datetime2}
\usepackage{expl3}

\begin{document}

\ExplSyntaxOn

\int_new:N \countresult

\cs_generate_variant:Nn \regex_count:nnN {nVN}

\cs_new:Npn \count_segment:n #1 {
    \tl_gset:Nx \g_tmpa_tl {#1}
    \exp_args:NNV \str_gset:Nn \g_tmpa_str {\g_tmpa_tl }
    \par input:~\tl_use:N \g_tmpa_str \ (length:~\str_count:N \g_tmpa_str)
    % discard consecutive spaces
    \regex_replace_all:nnN {[\s]{2,}} {\ } \g_tmpa_str
    \par after~replacement:~\tl_use:N \g_tmpa_str \ (length:~\str_count:N \g_tmpa_str)
    % discard start/end spaces
    \tl_gtrim_spaces:N \g_tmpa_str
    \par after~strip:~\tl_use:N \g_tmpa_str \ (length:~\str_count:N \g_tmpa_str)
    \str_if_empty:NTF \g_tmpa_str {
        \int_gset:Nn \countresult {0}
    } {
        \regex_count:nVN {\s} \g_tmpa_str \l_tmpa_int
        \int_gset:Nn \countresult {\l_tmpa_int + 1}
    }
}

\newcommand{\countsegment}[1]{
\count_segment:n {#1}
\par\textbf{result: \int_use:N \countresult}
}

\ExplSyntaxOff

\countsegment{Hello, my name is John}
\countsegment{\space 1,\space \space \space a,\space ,\space ,\space \space \space ,\space bcde\space}

\DTMNow

\end{document}

Output

input: Hello, my name is John (length: 22)
after replacement: Hello, my name is John (length: 22)
after strip: Hello, my name is John (length: 22)
result:5
input: 1, a, , , , bcde (length: 22)
after replacement: 1, a, , , , bcde (length: 18)
after strip: 1, a, , , , bcde (length: 16)
result:6
2020-06-12 18:43:32-04:00