这次语言测试为什么失败了?

这次语言测试为什么失败了?

我的问题是以下代码:

\documentclass{article}
\usepackage[english]{babel}
\begin{document}
\def\suplang{english}
\ifx\languagename\suplang
    Supported language: \languagename
\else 
    Not supported language: \languagename
\fi
\end{document}

结果是“不支持的语言:英语”,而不是“支持的语言:英语”。我做错了什么?

答案1

出于实施原因,替换文本的\languagename第一个字符的类别代码为 12;就此而言\ifx

e11 n11 g11 l11 i11 s11 h11

e12 n11 g11 l11 i11 s11 h11

不同的。事实上,如果你这样做

\documentclass{article}
\usepackage[english]{babel}
\begin{document}
\edef\suplang{\string english}
\ifx\languagename\suplang
    Supported language: \languagename
\else
    Not supported language: \languagename
\fi
\end{document}

那么输出是

在此处输入图片描述

你有必要做那项生意吗?当然不需要了。

\usepackage{pdftexcmds} % to work with all engines
\makeatletter
\newcommand{\supported}[3]{%
  \ifnum\pdf@strcmp{\languagename}{#1}=\z@
     \expandafter\@firstoftwo
  \else
     \expandafter\@secondoftwo
  \fi
  {#2}{#3}%
}
\makeatother

然后

\supported{suplang}
  {Supported language: \languagename}
  {Not supported language: \languagename}

将工作。

\documentclass{article}
\usepackage[english]{babel}
\usepackage{pdftexcmds} % to work with all engines
\makeatletter
\newcommand{\supported}[3]{%
  \ifnum\pdf@strcmp{\languagename}{#1}=\z@
     \expandafter\@firstoftwo
  \else
     \expandafter\@secondoftwo
  \fi
  {#2}{#3}%
}
\makeatother

\def\suplang{english}

\begin{document}

\supported{\suplang}
  {Supported language: \languagename}
  {Not supported language: \languagename}

\end{document}

对于真分支和假分支的替代定义\else\fi

\documentclass{article}
\usepackage[english]{babel}
\usepackage{pdftexcmds} % to work with all engines
\makeatletter
\newcommand{\issupported}[1]{%
  TT\fi\ifnum\pdf@strcmp{\languagename}{#1}=\z@
}
\makeatother

\def\suplang{english}

\begin{document}

\if\issupported\suplang
  Supported language: \languagename
\else
  Not supported language: \languagename
\fi

\end{document}

答案2

回答egreg 已经解释了问题中例子出现意外结果的原因,并且给出了解决问题的几种方法。

iflang将比较的内部内容包装\languagename在一个简单的宏中\IfLanguageName。问题的例子变成:

\documentclass{article}
\usepackage[english]{babel}
\usepackage{iflang}
\begin{document}
\IfLanguageName{english}{%
    Supported language: \languagename
}{%
    Not supported language: \languagename
}
\end{document}

结果

相关内容