在LaTeX中拆分逗号分隔的参数

18

我试图构建一个类似于LaTeX中的\cite{}命令,它接受逗号分隔的参数列表,格式如下:

\cite{Wall91, Schwartz93}

我想要将每个逗号分隔的参数列表中的项目传递给另一个命令,并返回单个结果的串联。我想象它可能是这样的:

\newcommand{\mycite}[1]{%
  \@for\var:=\split{#1} do{%
    \processCitation{\var}%
  }%
}

希望能够提供有关LaTeX中字符串操作、变量和循环的文献资料!

另外,是否有办法再次使用逗号将各个结果合并在一起?

谢谢!

1个回答

19

使用 Roberto 提供的链接,我得到了以下解决方案:

\makeatletter

% Functional foreach construct 
% #1 - Function to call on each comma-separated item in #3
% #2 - Parameter to pass to function in #1 as first parameter
% #3 - Comma-separated list of items to pass as second parameter to function #1
\def\foreach#1#2#3{%
  \@test@foreach{#1}{#2}#3,\@end@token%
}

% Internal helper function - Eats one input
\def\@swallow#1{}

% Internal helper function - Checks the next character after #1 and #2 and 
% continues loop iteration if \@end@token is not found 
\def\@test@foreach#1#2{%
  \@ifnextchar\@end@token%
    {\@swallow}%
    {\@foreach{#1}{#2}}%
}

% Internal helper function - Calls #1{#2}{#3} and recurses
% The magic of splitting the third parameter occurs in the pattern matching of the \def
\def\@foreach#1#2#3,#4\@end@token{%
  #1{#2}{#3}%
  \@test@foreach{#1}{#2}#4\@end@token%
}

\makeatother

使用示例:

% Example-function used in foreach, which takes two params and builds hrefs
\def\makehref#1#2{\href{#1/#2}{#2}}

% Using foreach by passing #1=function, #2=constant parameter, #3=comma-separated list
\foreach{\makehref}{http://stackoverflow.com}{2409851,2408268}

% Will in effect do
\href{http://stackoverflow.com/2409851}{2409851}\href{http://stackoverflow.com/2408268}{2408268}

这个该怎么使用呢?你能给个例子吗? - AVB
谢谢提供示例!问题和答案都加一分。 你介意看一下这里吗:https://dev59.com/RkzSa4cB1Zd3GeqPmGPU 也许你会有想法。 - AVB
没问题。谢谢你的支持。看一下我在你的帖子里给出的解决方案吧! - Christopher Oezbek
这个很好用。但是,对于包含下划线的字符串(例如具有下划线的引用),它不起作用。我猜我不应该这样做? - vy32

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接