Reputation: 33
I want to let the user enter integers in the following ways:
Numbers separated by commas: 1,3,122,64000,27 etc
Ranges of numbers: 37-2000
A mixture of the above: 55,2,1-10000,65000-65007,2182
How can I parse a string that may be in any of the forms above an end up with a List of int?
So for example: 1-5,6,7-8 should give a list containing the ints 1,2,3,4,5,6,7,8
I'm pretty new to C# so some example code would be greatly appreciated. Thanks.
Upvotes: 2
Views: 1903
Reputation: 117124
This works:
var query =
from x in text.Split(',')
let y = x.Split('-')
let b = int.Parse(y[0].Trim())
let e = int.Parse(y[y.Length - 1].Trim())
from n in Enumerable.Range(b, e - b + 1)
select n;
var result = query.ToList();
I would suggest adding some error handling, but if your input is in the correct format this works.
** EDIT**: The .NET 2.0 version.
var result = new List<int>();
foreach (var x in text.Split(','))
{
var y = x.Split('-');
var b = int.Parse(y[0].Trim());
var e = int.Parse(y[y.Length - 1].Trim());
for (var n = b; n <= e; n++)
{
result.Add(n);
}
}
Much the same... :-)
Upvotes: 2
Reputation: 514
Tokenise the string based on the ',' then parse that list of individual numbers or ranges.
From memory there is a Split(..) method on List that you can use to get the tokens. Then just test fot the presence of a '-' (if its the first character then its negative, not a range obviously).
Upvotes: 0
Reputation: 44605
String.split splitting by comma , will give you all you need then if a group contains - split for it again and you have the two range values
Upvotes: 2