字符串分割循环

字符串分割循环

我想循环\score,但是它提示错误

! Undefined control sequence.
\goforeach #1->\foreach 
                        \num in {#1} { the value is \num } 
l.28 ...ndafter\goforeach\expandafter\myfunc\textA

谁能帮助我,这是我的代码:

\documentclass{article}
\usepackage{csvsimple}
\usepackage{xparse}
\usepackage{filecontents}
\usepackage{datatool}

\DTLsetseparator{`}
\DTLloaddb{tabscores}{reportData.csv}
\DTLgetvalue{\score}{tabscores}{1}{2}%score value is 6,1,7.3,2,3.3


\NewDocumentCommand{\myfunc}{O{,} >{\SplitList{,}}m}{
    \def\itemdelim{\def\itemdelim{#1}}% Define list separator with one delay
    \ProcessList{#2}{\myitem}}

\newcommand\myitem[1]{\itemdelim${#1}$}

\newcommand{\goforeach}[1]{%
    \foreach \num in {#1}
    {
        the value is \num
    }
}

\begin{document}
\def\textA{\score}
\myfunc{\score}
\expandafter\goforeach\expandafter\myfunc\textA
\end{document}

答案1

经过一些猜测,我可以为您提供一个可以满足您需求的宏。

\begin{filecontents*}{\jobname.csv}
x`list
A`6,1,7.3,2,3.3
\end{filecontents*}

\documentclass{article}
\usepackage{xparse}
\usepackage{datatool}

\DTLsetseparator{`}
\DTLloaddb{tabscores}{\jobname.csv}
\DTLgetvalue{\score}{tabscores}{1}{2}

\ExplSyntaxOn

\NewDocumentCommand{\myfunc}{O{,}mm}
 {
  \seq_set_split:NnV \l_tmpa_seq {#1} #2
  \seq_map_function:NN \l_tmpa_seq #3
 }
\cs_generate_variant:Nn \seq_set_split:Nnn { NnV }

\ExplSyntaxOff

\newcommand\myitem[1]{\item $#1$}

\begin{document}

\begin{itemize}
\myfunc\score\myitem
\end{itemize}

\end{document}

在此处输入图片描述

答案2

要使用该\foreach \num in {..}语法,您需要pgffor

在此处输入图片描述

\documentclass{article}

\usepackage{xparse}
\usepackage{pgffor}

\def\score{6,1,7.3,2,3.3}

\NewDocumentCommand{\myfunc}{O{,} >{\SplitList{,}}m}{
    \def\itemdelim{\def\itemdelim{#1}}% Define list separator with one delay
    \ProcessList{#2}{\myitem}}

\newcommand\myitem[1]{\itemdelim${#1}$}

\newcommand{\goforeach}[1]{%
    \foreach \num in {#1}
    {%
        the value is \num\par
    }
}

\begin{document}

\myfunc{\score}

\expandafter\goforeach\expandafter{\score}

\end{document}

请注意我如何将您的调用格式更改为\goforeach,它不应该使用 的输出\myfunc

相关内容