# How to split parameter and assign result into separate variables or an array?

I need a pretty simple thing - when I get a macro parameter which is a string delimited with commas, can I split it and assign resulting strings into an array?

In short, I'd like to write something like this:

\newcommand{\test}[1]{
\def\array = \parse{#1}{,}
}


So I could later use it like this:

\someOtherMacro{\array[1]}


I was looking at the other answers, but I'm not able to find something really simple for this task (just parsing string and assigning results).

• You mean something like this: \def\com#1,#2{\def\array{#1}}. i.e. \com{Hallo,Tübb} will result in \array -> Hallo. – MaestroGlanz Nov 11 '16 at 15:02
• Related: Data structures for TeX – Werner Nov 11 '16 at 17:01

You can consider using arrayjobx:

\documentclass{article}

\usepackage{arrayjobx}

\makeatletter
\makeatother

\newcommand{\someOtherMacro}{\textbf}

\begin{document}

\newarray\mynames

1: \mynames(1) and \someOtherMacro{\mynames(2)} and \mynames(3)

2: \mynames(1) and \mynames(2) and \someOtherMacro{\mynames(3)}

\end{document}


The listofitems package is very powerful in this regard. The first example parses based on a , separator.

The 2nd example is a two-tiered parsing, first by way of \\, and then again, using a space separator.

Parsing to n-tiers poses no problem for the package. It also has options to discard blank array elements, if desired.

In both cases, leading/trailing spaces have been excised, by using the star form of the \readlist invocation.

\documentclass{article}
\usepackage{listofitems}
\begin{document}
\setsepchar{,}
\readlist*\parsed{This, is, my , list, of words}
There are \parsedlen{} items in list

Here are the items:
\showitems\parsed

item 4 is \parsed[4]''.

\setsepchar{\\/ }
This is a test\\
of the\\
}

Here is the other list:
\showitems\multiparsed

Row 2 is \multiparsed[2].''

2nd word of row 3 is \multiparsed[3,2]''.
\end{document}


• Thank you very much! But I'm working on a shared document on OverLeaf and it doesn't support listofitems. Do you have any other solution? – Eenoku Nov 11 '16 at 16:12

It's very easy with expl3.

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\definearray}{mm}
{
\seq_new:c { g_eenoku_array_#1_seq }
\seq_gset_split:cnn { g_eenoku_array_#1_seq } { , } { #2 }
}
\cs_generate_variant:Nn \seq_gset_split:Nnn { c }
\NewDocumentCommand{\usearray}{mm}
{
\seq_item:cn { g_eenoku_array_#1_seq } { #2 }
}
\ExplSyntaxOff

\definearray{names}{Moe,Larry,Curly}

\begin{document}

\usearray{names}{1}

\usearray{names}{2}

\usearray{names}{3}

\end{document}