\@for 不與 \StrSubstitute 組合

\@for 不與 \StrSubstitute 組合

我想將一個以空格分隔的字串分成幾個部分,並為每個部分產生程式碼。顯然 TeX 本身就可以處理逗號分隔的字串,所以我嘗試寫一個改編版本

\usepackage{xstring}    
\makeatletter
\@for\next:=foo,bar,baz\do{X \next Y} \\
\StrSubstitute{foo bar baz}{ }{,} \\
\@for\next:=\StrSubstitute{foo bar baz}{ }{,}\do{X \next Y}
\makeatother

在此輸入影像描述

逗號分隔字串的第一行輸出是正確的。顯示空格分隔字串轉換為對應的逗號分隔字串的輸出的第二行是正確的。

但是,在第三行(第二行)中\@for,字串沒有被拆分。

為什麼不,我該如何解決這個問題?

答案1

\StrSubstitute有多個可選參數且無法擴展,因此無法使用 TeX 的輸出\StrSubstitute並將其再次輸入到 TeX 的輸入流中。

可以將 的結果儲存\StrSubstitute到臨時巨集並使用該巨集作為\@for\next...的輸入。

\documentclass{article}

\usepackage{xstring}   

\begin{document} 
\makeatletter
\@for\next:=foo,bar,baz\do{X \next Y} \\
\StrSubstitute{foo bar baz}{ }{,} \\
\StrSubstitute{foo bar baz}{ }{,}[\@stuff]
\@for\next:=\@stuff\do{X \next Y}
\makeatother
\end{document}

在此輸入影像描述

答案2

如果要求循環遍歷空格分隔的列表,則無需用逗號替換空格並循環遍歷逗號分隔的列表。實現該替換可能已經需要迭代空間的能力。

例如,這會迭代空格分隔的單字,並將每個單字放入 fbox 中。

在此輸入影像描述

\documentclass{article}

\def\zz#1{\zzz#1 \! }

\def\zzz#1 {\ifx\!#1\else\fbox{#1} \expandafter\zzz\fi}
\begin{document}

\zz{foo bar baz}

\end{document}

答案3

listofitems套件可以根據指定的多個字元進行解析,此處給出為空格和逗號,。因此, 的一個定義可以\setsepchar解決所有情況,而無需使用xstring。編輯以體現宏觀解決方案\processlist

\documentclass{scrartcl}
\usepackage{listofitems}
\setsepchar{ ||,}%
\newcommand\processlist[1]{%
  \readlist\mylist{#1}%
  \foreachitem\next\in\mylist{X \next Y}%
}
\begin{document}
\processlist{foo,bar,baz}

\processlist{foo bar baz}
\end{document}

在此輸入影像描述

相關內容