【问题标题】:Split comma-separated parameters in LaTeX在 LaTeX 中拆分逗号分隔的参数
【发布时间】:2010-03-08 15:25:04
【问题描述】:

我正在尝试构建一个类似于 LaTeX \cite{} 的命令,它接受像这样以逗号分隔的参数列表

\cite{Wall91, Schwartz93}

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

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

有关 LaTeX 中的字符串操作、变量和循环的文献会很棒!

另外:有没有办法再次使用逗号加入单个结果?

谢谢!

【问题讨论】:

    标签: string latex split variadic-functions


    【解决方案1】:

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

    【讨论】:

    • 如何使用它?你能举个例子吗?
    • 感谢您的示例!问答+1。你介意看看这里吗:stackoverflow.com/questions/2389081也许你会有一个想法。
    • 没问题。感谢您的投票。看看我在你的帖子中给出的解决方案!
    • 这很好用。但是,它不适用于传递包含非文本下划线的字符串(例如具有下划线的引用)。我想我不应该那样做?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    • 2015-04-01
    • 2015-03-07
    • 2010-11-06
    • 1970-01-01
    相关资源
    最近更新 更多