简体   繁体   中英

Parsing String Into List of Integers with Ranges

I have a bunch of strings I would like to parse that all look like this:

"1001, 1003, 1005-1010"
"1015"
"900-903"
"200, 202-209, 211-220"

Sometimes these strings will be just one integer, sometimes multiple separated by commas, and sometimes a range, and the latter two can appear simultaneously in a single string in any order.

What I would like to do is create a function that takes in the string and returns a collection of integers by parsing the string. So for example the first string should return:

[1001, 1003, 1005, 1006, 1007, 1008, 1009, 1010]

What are some smart ways to do this in .NET 4.0?

.NET 4.0 means you got LINQ available, so you should probably use it:

var input = "1001, 1003, 1005-1010";

var results = (from x in input.Split(',')
               let y = x.Split('-')
               select y.Length == 1
                 ? new[] { int.Parse(y[0]) }
                 : Enumerable.Range(int.Parse(y[0]), int.Parse(y[1]) - int.Parse(y[0]) + 1)
               ).SelectMany(x => x).ToList();

Traditional loop that might be easier to read:

string input = "1001, 1003, 1005-1010";

List<int> result = new List<int>();
foreach (string part in input.Split(','))
{
    int i = part.IndexOf('-');
    if (i == -1)
    {
        result.Add(int.Parse(part));
    }
    else
    {
        int min = int.Parse(part.Substring(0, i));
        int max = int.Parse(part.Substring(i + 1));
        result.AddRange(Enumerable.Range(min, max - min + 1));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM