C# string with comma separated values into array of ints

  • Thread starter Thread starter idog
  • Start date Start date
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);
}
 
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.
 
Back
Top