C# string with comma separated values into array of ints

I

idog

If I start off with a string which contains comma separated ints. I
want to move this into an int array so i can do sorting.

I thought I might get this to work:

int[] test = {textBox1.Text};

What would be the best way to accomplish this?

This is what i came up with:

private void button1_Click(object sender, System.EventArgs e)
{
int [] test;

test = commaStringToArray(textBox1.Text);

// ok here i will do stuff to test[], like sorting
//

textBox2.Text = arrayToCommaString(test);
}

private int[] commaStringToArray(string strComma)
{
string [] strArray;

strArray = strComma.Split(new char[] {','});
int [] intArray = new int [strArray.Length];

for (int i = 0; i < strArray.Length; i++)
intArray = int.Parse(strArray);

return intArray;
}

private string arrayToCommaString(int[] intArray)
{
string strOut = "";

foreach (int i in intArray)
strOut += ", " + i.ToString();

return strOut.Remove(0,2);
}
 
N

Nicholas Paldino [.NET/C# MVP]

idog,

What you have is basically the easiest way. You can get more
performance, but the time to develop that solution could be high (you would
have to iterate through each character, parsing when you get to commas, and
then generating the integer and performing the calcs on the fly, etc, etc).

Also, unless you can guarantee that the string is in the format you want
(integer, comma, integer, etc, etc), you might want to put some error
checking code in there.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top