使用 xstring 計算字元數

使用 xstring 計算字元數

我有以下代碼,由作者 Christian Tellechea 提供xstring,非常感謝。這個想法是計算結構內屬於預先定義列表的字元數。

\documentclass{article}
\usepackage{xstring}
\usepackage{blindtext}
\makeatletter
\def\countoccurs#1#2{%
    \saveexpandmode\expandarg
    %\exploregroups
    \expandafter\def\expandafter\tmp@list\expandafter{\list,}%
    \let\nboccur\z@
    \loop
        \unless\ifx\empty\tmp@list
            \StrCut\tmp@list,\tmp@cs\tmp@list
            %\StrCount{\noexpand#2}\tmp@cs[\tmp@cs]%
            \StrCount{#2}\tmp@cs[\tmp@cs]%
            \edef\nboccur{\number\numexpr\nboccur+\tmp@cs}%
    \repeat
    \restoreexpandmode
}
%\def\list{12,a,bc,9} % list can also be defined as this
\def\list{%
a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,Q,r,s,t,u,v,w,x,y,z,%
A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,S,X,Y,Z,%
1,2,3,4,5,6,7,8,9,0,%
}
\def\countenv#1{#1\countoccurs\list{#1}}
\makeatother

\begin{document}
\countenv{\begin{tabular}{ll} a & b \\ a & c \end{tabular}}\par
I counted: \nboccur.

\noindent\hrulefill

\countenv{\textbf{D}2345}\par
I counted: \nboccur.

\noindent\hrulefill

\countenv{\blindtext}\par
I counted: \nboccur.

\noindent\hrulefill

%\countoccurs\list{12987d bc abcabc999}
\countenv{12987d bc abcabc999}\par
I counted: \nboccur.

\noindent\hrulefill
\end{document}

正如您在輸出中看到的,第一個和最後一個計數是正確的,但其他計數不正確。我嘗試使用\exploregroupsand\noexpand#2但運氣好所有提供的例子。例如,它\noexpand#2修正了第二個輸出,但嚴重影響了第一個和第三個輸出。有沒有一種方法適合所有人?

答案1

\blindtext不擴展為某些文本,但在到達文本之前執行許多(不可擴展的)命令。

您可以嘗試使用kantlipsum, ,它可以定義擴展到其段落之一的巨集。

\documentclass{article}
\usepackage{xstring}

\usepackage{kantlipsum}
\kantdef\mytext{1}

\makeatletter
\def\countoccurs#1#2{%
    \saveexpandmode\expandarg
    %\exploregroups
    \expandafter\def\expandafter\tmp@list\expandafter{\list,}%
    \let\nboccur\z@
    \loop
        \unless\ifx\empty\tmp@list
            \StrCut\tmp@list,\tmp@cs\tmp@list
            %\StrCount{\noexpand#2}\tmp@cs[\tmp@cs]%
            \StrCount{#2}\tmp@cs[\tmp@cs]%
            \edef\nboccur{\number\numexpr\nboccur+\tmp@cs}%
    \repeat
    \restoreexpandmode
}
%\def\list{12,a,bc,9} % list can also be defined as this
\def\list{%
a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,Q,r,s,t,u,v,w,x,y,z,%
A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,S,X,Y,Z,%
1,2,3,4,5,6,7,8,9,0,%
}
\def\countenv#1{#1\countoccurs\list{#1}}
\makeatother

\begin{document}
\countenv{\begin{tabular}{ll} a & b \\ a & c \end{tabular}}\par
I counted: \nboccur.

\noindent\hrulefill

\countenv{\textbf{D}2345}\par
I counted: \nboccur.

\noindent\hrulefill

\countenv{\mytext}\par
I counted: \nboccur.

\noindent\hrulefill

%\countoccurs\list{12987d bc abcabc999}
\countenv{12987d bc abcabc999}\par
I counted: \nboccur.

\noindent\hrulefill
\end{document}

之後長的時間(在我的機器上是 15 秒,這是很長處理時間),你就明白了。

在此輸入影像描述

相關內容