xstring으로 문자 수 계산

xstring으로 문자 수 계산

작성자 Christian Telechea 가 제공한 다음 코드가 있습니다 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초입니다.매우 긴처리 시간), 이것을 알 수 있습니다.

여기에 이미지 설명을 입력하세요

관련 정보