blah blah blah is here! blah blah » Close

up1down
link

I have a textbox with the following values : 4,5,6,7,8,9,10,11,12,13,15
I want these values to be split into `x` string arrays with `y` values in each array.

For example extract into 3 arrays with 4 numbers in each :

int x = 3;
string[] batch;

batch[0] = "4,5,6,7"
batch[1] = "8,9,10,11"
batch[2] = "12,13,15"

For example extract into 5 arrays with 2 numbers in each :
int x = 5;
string[] batch;

batch[0] = "4,5"
batch[1] = "6,7"
batch[2] = "8,9"
batch[3] = "10,11"
batch[4] = "12,13"
batch[5] = "15"

I've tried Regex.split but I can't get it done... Please help

last answered 2 years ago

1 answers

up1down
link

This method should do it though your second example should be 6 arrays (not 5) of 2 values. As you'll see, I've tried to adjust the arguments passed to the method so that an exception is never thrown:

private static string[][] GetBatches(string text, int x, int y)
{
if (x < 1) x = 1;
if (y < 1) y = 1;
if (text == null) text = "";
string[] elements = text.Split(',');
int len = elements.Length;
if (x > len)
{
x = len;
y = 1;
}
if (y > len)
{
x = 1;
y = len;
}
int last = y; // number in last batch
if (x * y > len)
{
y++;
do
{
y--;
last = y - x * y + len; // adjust last batch to fit
}
while (last < 0);
}
else if (x * y < len)
{
last += len - x * y; // add surplus to last batch
}
string[][] batch = new string[x][];
for(int i = 0; i < x - 1; i++)
{
batch[i] = new string[y];
Array.Copy(elements, y * i, batch[i], 0, y);
}
batch[x - 1] = new string[last];
Array.Copy(elements, (x - 1) * y, batch[x - 1], 0, last);
return batch;
}

and call with something like this:
string[][] batch = GetBatches(textBox1.Text, 3, 4);
string message = "";
for(int i = 0; i < batch.Length; i++)
{
message += String.Format("batch[{0}] = \"{1}\"\r\n", i, String.Join(",", batch[i]));
}
MessageBox.Show(message);

oostadr
15

You're right it should have bin an array of 5 instead of 6. Thx for the answer, this will do.

Feedback