![为什么结果 \StrCount 不能直接使用](https://linux22.com/image/361313/%E4%B8%BA%E4%BB%80%E4%B9%88%E7%BB%93%E6%9E%9C%20%5CStrCount%20%E4%B8%8D%E8%83%BD%E7%9B%B4%E6%8E%A5%E4%BD%BF%E7%94%A8.png)
我想将从 \StrCount(package xstring) 获得的数字存储到计数器中,如下所示,但它不起作用,并给出错误消息。有人能告诉我原因吗?谢谢。
\documentclass[12pt,a4paper]{article}
\usepackage{xstring,ifthen}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}
some text
\newcounter{columnnumber}
\newcommand{\getcolumnnumber}[1]{%
\IfSubStr{#1}{:}
{\setcounter{columnnumber}{\StrCount{#1}{:}}}
%{\setcounter{columnnumber}{\StrCount{#1}{:} + 1}}
{\setcounter{columnnumber}{1}}
}%
\getcolumnnumber{1:2:3:4}
\thecolumnnumber
\end{document}
答案1
我认为您需要将 的输出保存\StrCount
到宏中(此处\tmp
)。另外,您似乎想将计数器加 1,因此列号是冒号数 + 1,为此您可以使用\stepcounter
。
至于原因,它与扩展有关,\StrCount
在那种情况下使用时不会扩展。(或类似的东西。)
\documentclass[12pt,a4paper]{article}
\usepackage{xstring,ifthen}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}
some text
\newcounter{columnnumber}
\newcommand{\getcolumnnumber}[1]{%
\IfSubStr{#1}{:}
{\StrCount{#1}{:}[\tmp]\setcounter{columnnumber}{\tmp}\stepcounter{columnnumber}}
{\setcounter{columnnumber}{1}}
}%
\getcolumnnumber{1:2:3:4}
\thecolumnnumber
\end{document}