使用变量的 If-if-else 表达式

使用变量的 If-if-else 表达式

我正在尝试创建一个包含学士论文布局的文档类,并希望使其尽可能通用。在我的标题页(在文档类中定义,而不是主文档中)中应出现如下一行:

Handed in by {\@gender} {\@author} on {\@handindate}.

使用以下命令创建变量:

\newcommand{\@handindate}{\@handindate}
\newcommand{\handindate}[1]{\renewcommand{\@handindate}{#1}}

\newcommand{\@gender}{Unknown}
\newcommand{\gender}[1]{\renewcommand{\@gender}{#1}}

我希望 LaTeX\@gender用“先生”替换“女士”,\@gender=male用“先生”替换“女士”,\@gender=female\@gender其他任何内容替换“先生”。

我想过使用\ifcase-command,但据我所知,此命令仅接受数字作为输入,但我想使用变量作为输入。我基本上需要的是类似“如果值等于 male,则打印<text1>,如果值等于 female,则打印,<text2>在其他所有情况下都打印<>”的语法,但我不太擅长编程,所以有人可以帮忙吗?

答案1

通过与“男性”和“女性”进行比较进行检查:

\documentclass{article}

\makeatletter
\newcommand{\Handed}{%
  \par
  Handed in by \Apply@Gender\@Author\space on \@Handindate
  \par
}

\newcommand{\@Gender}{Unknown}
\newcommand{\@Author}{Unknown}
\newcommand{\@Handindate}{Unknown}

\newcommand{\Gender}[1]{\renewcommand{\@Gender}{#1}}
\newcommand{\Author}[1]{\renewcommand{\@Author}{#1}}
\newcommand{\Handindate}[1]{\renewcommand{\@Handindate}{#1}}

\newcommand{\Apply@Gender}{%
  \begingroup
  \long\def\@male{male}\long\def\@female{female}%
  \ifx\@Gender\@male 
    Mr.~%
  \else
    \ifx\@Gender\@female
      Mrs.~%
    \fi
  \fi
  \endgroup
}
\makeatother

\begin{document}

\Gender{male}
\Author{G. Byron}
\Handindate{2016-06-21}

\Handed

\bigskip

\Gender{female}
\Author{M. Wollstonecraft}
\Handindate{2016-06-22}

\Handed

\bigskip

\Gender{whatever}
\Author{The Creature}
\Handindate{2016-06-23}

\Handed

\end{document}

在此处输入图片描述

答案2

此示例使用xstring、 和pgffor创建一个遍历可接受短语列表的 lopp。添加更多短语就像将它们添加到列表中一样简单。

\def\genderInput{%
%Input: <input gender>/<output phrase>,% (without the <>, ending by commma)
female/Mrs.,%
male/Mr.,%
boy/young Mr.,%
girl/Miss,%
none/}

请注意,在英国,这将是先生太太没有点。

输出

在此处输入图片描述

代码

\documentclass[11pt]{article}
\usepackage{xstring}
\usepackage{pgffor}

\def\genderInput{%
%Input: <input gender>/<output phrase>,% (without the <>, ending by commma)
female/Mrs.,%
male/Mr.,%
boy/young Mr.,%
girl/Miss,%
none/}

\makeatletter
\newcommand{\@handindate}{\@handindate}
\newcommand{\handindate}[1]{\renewcommand{\@handindate}{#1}}

\newcommand{\@gender}{Unknown}
\newcommand{\gender}[1]{\renewcommand{\@gender}{#1}}


\gender{male}
\author{Joe Doe}

\newcommand{\getName}{%
\foreach \theGender/\theString in \genderInput{%
    %\theGender - \theString
    %\theGender
    \IfSubStr{\@gender}{\theGender}{%
        \theString~%
        \breakforeach}{%
        %invalid gender input %\texttt{\slash}
        }%
    }\@author%
}
\makeatother
\begin{document}
This document was written by \getName.


\gender{female}
\author{Jane Doe}

This document was written by \getName.


\gender{}
\author{Duck}

This document was written by \getName.

\gender{boy}
\author{Jimmy Nogood}

This document was written by \getName.

\gender{girl}
\author{Lily Johnson}

This document was written by \getName.
\end{document}

相关内容