如何替换 LaTeX 中的最后一个字符?

如何替换 LaTeX 中的最后一个字符?

我需要编写一个命令,其中最后一个字符的出现取决于是否立即再次出现相同的命令(任何类型的空格除外)或中间是否出现文本。

以下最小工作示例通过不输出前一个命令的最后一个字符(直到我告诉它)来实现我想要的功能 - 但我总是必须记住提及\Finish否则输出会被破坏,所以我想要某种不那么脆弱的方式:

\documentclass{article}
\makeatletter
\usepackage{ifthen}

\def\@tmp{}

\newcommand\test[2]{%
    \ifthenelse{\equal{\@tmp}{#2}}{}{\@tmp{}}%
    #1%
    \def\@tmp{#2}%
}

\newcommand\Finish{\@tmp{}\def\@tmp{}}

\makeatother
\begin{document}

\test{1}{2}\test{1}{2}\Finish{} (output: 112)

\test{1}{2}\test{3}{4}\Finish{} (output: 1234)

\test{1}{2}\test{3}{4} (output: 123 - missing 4 because I forgot Finish)

\test{5}{6}\Finish (output: 456 - the missing 4 showed up here.)

\end{document}

答案1

我相信这会产生您想要的输出。但我认为如果您能稍微澄清一下您想要什么,效果会更好。

\documentclass{article}

\usepackage{ifthen}
\usepackage{etoolbox}
\newbool{first_of_two}

\makeatletter

\def\@tmp{}

\newcommand\test[2]{%
  \@ifnextchar\test
  {\@first@of@two@test{#1}{#2}}
  {\@singleton@test{#1}{#2}}%%
}

\def\@first@of@two@test#1#2{%%
  \ifthenelse{\equal{\@tmp}{#2}}{}{\@tmp}%%
  \booltrue{first_of_two}%%
  \def\@tmp{#2}%%
  #1}

\def\@singleton@test#1#2{%%
  \def\ae@continue{}%%
  \ifbool{first_of_two}
    {\let\ae@continue\@preceded@by@same}
    {\let\ae@continue\@singleton@isolated}%%
  \boolfalse{first_of_two}%%
  \ae@continue{#1}{#2}%%
  \def\@tmp{}%%
}

\def\@preceded@by@same#1#2{%%
  \ifthenelse{\equal{\@tmp}{#2}}{#1#2}{\@tmp#1#2}\boolfalse{first_of_two}}

\def\@singleton@isolated#1#2{#1#2}

\makeatother

\begin{document}

\test{1}{2}   \test{1}{2} (output: 112)

\test{2}{3} a  \test{2}{3} (output: 23a 23)

next line: 12:354

\test{1}{2}\test{3}{4}\test{5}{4}    (output: 1234)

\test{1}{2}\test{3}{4}    (output: 1234 - no missing 4 just because I forgot Finish)

\test{5}{6}               (output is not: 456 - no missing 4 showing up here.)

\end{document}

在此处输入图片描述

相关内容