简体   繁体   English

将字符串解析为带范围的整数列表

[英]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中,有哪些聪明的方法可以做到这一点?

.NET 4.0 means you got LINQ available, so you should probably use it: .NET 4.0意味着您可以使用LINQ,因此您应该使用它:

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));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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