我想测试一个字符串在最终打印时是否为空。以下说明了我的问题,
\documentclass{article}
\usepackage{ifthen}
\newcommand{\isempty}[1]%
{
\ifthenelse{\equal{#1}{}}%
{EMPTY}% if #1 is empty
{FULL, it contains the string '#1'}% if #1 is not empty
}
\newcommand{\Something}{Something}
\newcommand{\Nothing}{}
\begin{document}
First the buffer is \isempty{\Something}.
Second the buffer is \isempty{\Nothing}.
{\em So far so good.} But
Third the buffer is \isempty{{\Nothing}}.
Forth the buffer is \isempty{\bf{\Nothing}}.
It says the string is Full with ''!
\end{document}
输出为
First the buffer is FULL, it contains the string ’Something’.
Second the buffer is EMPTY.
So far so good. But
Third the buffer is FULL, it contains the string ’’.
Forth the buffer is FULL, it contains the string ’’.
It says the string is Full with ”!
答案1
测试\ifthenelse{\equal{{}}{}}
正确地遵循了“错误”路径,因为第一个参数\equal
是不是为空,因为它包含一个空组。
您可以用不同的方式测试该参数是否不产生打印文本:
\newcommand{\ifnotext}[1]{%
\sbox0{#1}%
\ifdim\wd0=0pt
{EMPTY}% if #1 is empty
\else
{FULL, it contains the string '#1'}% if #1 is not empty
\fi
}
棘手的输入可能会欺骗\ifnotext
,但在您的情况下不会:现在\ifnotext{\Nothing}
会打印“EMPTY”。
答案2
如果您尝试确定文本的宽度是否为零,那么@egreg 的解决方案就是可行的方法。另一种方法是使用包\IfStrEqCase
中的xstring
方法来检查每个条件:
笔记:
- 这不是如果您想要测试大量的选项,那么这是一个很好的解决方案。
- 您还应该参考为什么 ifthen 包已经过时了?
代码:
\documentclass{article}
\usepackage{xstring}
\newcommand{\isempty}[1]{%
\IfStrEqCase{#1}{%
{\empty}{EMPTY 1}% if #1 is empty
{{\empty}}{EMPTY 2}% if #1 is {empty}
{\bf{\empty}}{EMPTY 3}% if #1 is {empty}
}[FULL, it contains the string '#1'] % if #1 is not empty
}
\newcommand{\Something}{Something}
\newcommand{\Nothing}{}
\begin{document}
First the buffer is \isempty{\Something}.
Second the buffer is \isempty{\Nothing}.
Third the buffer is \isempty{{\Nothing}}.
Fourth the buffer is \isempty{\bf{\Nothing}}.
{\em So far so good.} And No Buts
\end{document}