string - 在LaTeX中分割逗号分隔的参数

标签 string latex split variadic-functions

我正在尝试构建类似于LaTeX \cite{}的命令,该命令接受以逗号分隔的参数列表,如下所示

\cite{Wall91, Schwartz93}

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

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


LaTeX中有关字符串操作,变量和循环的文献非常棒!

另外:是否有一种方法可以再次使用逗号来合并各个结果?

谢谢!

最佳答案

使用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}

关于string - 在LaTeX中分割逗号分隔的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2402354/

相关文章:

java - 偶数长度字符串的字符串越界错误

latex - papaja 生成的 Rmarkdown 中使用 ragged2e 进行文本对齐

python - 如何插入大正斜杠来标记 matplotlib 轴

arrays - Ruby String Split on "\t"丢失 "\n"

r - 字符串分割的模式如何成为子字符串本身?

c++ - fscanf 不能正确处理字符串

android - 更改字符串数组中的项目时应用程序强制关闭,Android?

c - strcmp 在我的代码中不起作用

latex - 使用\bibentry 显示内联引用前面的数字

string - 在 SWIFT 中遇到逗号时将字符串换行