public static int[] StringToInts(string myString)
{
List<int> ints = new List<int>();
string[] strings = myString.Split(',');
foreach (string s in strings)
{
int i;
if (int.TryParse(s.Trim(), out i))
{
ints.Add(i);
}
}
return ints.ToArray();
}
Like that, but I wouldn't use the List (why use a generic and then
hard-code
it to use only one type?), I'd do something like:
string[] strings = myString.Split(',') ;
int[] ints = new int [ strings.Length ] ;
for ( int i = 0 ; i < string.Length ; i++ )
{
ints [ i ] = int.Parse ( strings [ i ] ) ; // Provide some protection
here
}
return ( ints ) ;
I would probably also provide for a list of seperators to be passed in,
rather than having the comma hard-coded.
The generic implementation would be good if you wanted a class that could
split the string and provide a list of values of some provided type. I'll
leave that as an exercise