
我想將一個以空格分隔的字串分成幾個部分,並為每個部分產生程式碼。顯然 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
答案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}