代码之家  ›  专栏  ›  技术社区  ›  Christopher Oezbek

乳胶中的分隔逗号分隔参数

  •  14
  • Christopher Oezbek  · 技术社区  · 14 年前

    我想建立一个类似于乳胶的命令 \cite{} ,接受逗号分隔的参数列表,如

    \cite{Wall91, Schwartz93}

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

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

    关于字符串操作、变量和乳胶中的循环的文献将是伟大的!

    还有:有没有一种方法可以再次使用逗号连接各个结果?

    谢谢!

    2 回复  |  直到 14 年前
        1
  •  17
  •   Christopher Oezbek    14 年前

    通过罗伯托的链接,我得出了这个解决方案:

    \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}
    
        2
  •  -3
  •   Rego    12 年前

    你可以用这个包裹 cite 喜欢

    \usepackage{cite}
    ...
    \cite{citation1, citation2, citation3}
    

    检查这个 link .