我有一个字符串"2-6,8,10-15,20-23"
我需要将其转换为数组中完全填充的数字范围,如下所示:
{2,3,4,5,6,8,10,11,12,13,14,15,20,21,22,23}
你有什么想法如何转换它吗?
发布于 2013-11-10 13:05:16
这段代码应该能做到这一点(在注释中描述了这个过程):
Dim s As String = "2-6,8,10-15,20-23" 'Your values
Dim values As New List(Of Integer)() 'Create an List of Integer values / numbers
For Each value As String In s.Split(","C) ' Go through each string between a comma
If value.Contains("-"C) Then 'If this string contains a hyphen
Dim begin As Integer = Convert.ToInt32(value.Split("-"C)(0)) 'split it to get the beginning value (in the first case 2)
Dim [end] As Integer = Convert.ToInt32(value.Split("-"C)(1)) ' and to get the ending value (in the first case 6)
For i As Integer = begin To [end] 'Then fill the integer List with values
values.Add(i)
Next
Else
values.Add(Convert.ToInt32(value)) 'If the text doesn't contain a hyphen, simply add the value to the integer List
End If
Next
发布于 2016-05-13 15:18:47
Mark在PluralSight有一门关于LINQ的课程,很好地解决了这个问题。使用LINQ,您可以使用下面的示例快速完成此操作。
string value = "7-10,2,5,12,17-18";
var result = value.Split(',')
.Select(x => x.Split('-'))
.Select(p => new { First = int.Parse(p.First()), Last = int.Parse(p.Last()) })
.SelectMany(x => Enumerable.Range(x.First, x.Last - x.First + 1))
.OrderBy(z=>z);
Split
从字符串中创建一个数组。第一个Select
创建一个数组,每个数组有一个或两个元素。第二个Select
创建一个匿名类型,根据数组值指示起始值和结束值。SelectMany
使用Enumerable.Range
方法从每个匿名对象创建一系列数字,然后将其扁平化为整数的IEnumerable
集合。最后,OrderBy
将数字放在报告和其他用途上。
发布于 2013-11-13 13:15:35
string numberString = "2-6,8,10-15,20-23";
List<int> cNumberString = getValidString(numberString);
List<int> getValidString(string str)
{
List<int> lstNumber = new List<int>();
string[] cNumberArray = str.Split(',');
for (int k = 0; k < cNumberArray.Length; k++)
{
string tmpDigit = cNumberArray[k];
if (tmpDigit.Contains("-"))
{
int start = int.Parse(tmpDigit.Split('-')[0].ToString());
int end = int.Parse(tmpDigit.Split('-')[1]);
for (int j = start; j <= end; j++)
{
if (!lstNumber.Contains(j))
lstNumber.Add(j);
}
}
else
{
lstNumber.Add(int.Parse(tmpDigit));
}
}
return lstNumber;
}
https://stackoverflow.com/questions/19889720
复制相似问题