Convert to an Array

G

Guest

How would I convert this string to an Array?
"243, 567, 324, 345"
Where each number becomes a new element in that Array.
Thanks
 
S

ShaneB

I'm not sure if you want a string array or an integer array but this should
help:

using System.Text.RegularExpressions;
....

Regex rx = new Regex(", ");
string[] myarray = rx.Split("243, 567, 324, 345"); // creates a string array
containing each number

foreach (string s in myarray)
{
// show the string version of this array item
MessageBox.Show("'" + s + "'");

// Convert it to an integer if you like
int myinteger = Int32.Parse(s);
// add the integer to an array here if you like...
}


ShaneB
 
P

Philipp Sumi

For a simple split like this one, you can easily use the Split function
of the String class. Check your online help for examples.

hth, Philipp
 
S

ShaneB

The reason I didn't mention string.split is because it won't work as
expected in his case. In the original poster's question, the string he
provided contained a space after each comma. That means the code would have
to look like this:

string s = "243, 567, 324, 345";
string[] myarray = s.Split(new char[]{',' , " "});

As a result, myarray will contains 8 items...because string.split split the
array on each occurance of each character.

Regex.Split() will split it properly and accepts a string input as well.

ShaneB
 

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