将字符串中的数字范围转换为整数列表

时间:2013-11-10 12:32:17

标签: c# arrays vb.net string range

我有一个字符串"2-6,8,10-15,20-23"

我需要将它转换为数组中完全填充的数字范围,如下所示:

{2,3,4,5,6,8,10,11,12,13,14,15,20,21,22,23}

您对如何转换它有什么想法吗?

5 个答案:

答案 0 :(得分:2)

这段代码可以解决问题(程序在评论中描述):

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

答案 1 :(得分:2)

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

答案 2 :(得分:2)

Mark Heath在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创建一个数组,每个数组包含1或2个元素。第二个Select创建一个匿名类型,指示基于数组值的起始值和结束值。 SelectMany使用Enumerable.Range方法从每个匿名对象创建一系列数字,然后将其展平为IEnumerable个整数集合。最后,OrderBy将数字放在报告和其他用途中。

答案 3 :(得分:1)

假设您的输入字符串总是正确格式化,您可以尝试这样的事情:

Public Function GetIntArray(input As String) As Integer()
  Dim splits() = input.Split(",")
  Dim result As New List(Of Integer)

  For Each s In splits
    If s.Contains("-") Then
      Dim low As Integer = s.Split("-")(0)
      Dim hi As Integer = s.Split("-")(1)

      For i = low To hi
        result.Add(i)
      Next
    Else
      result.Add(s)
    End If
  Next
  Return result.ToArray
End Function

基本思路是沿着逗号分隔符拆分输入字符串,然后检查该字符串是单个数字还是范围。

答案 4 :(得分:0)

使用Array.ConvertAll method

Dim stringArray = {"123", "456", "789"}
Dim intArray = Array.ConvertAll(stringArray, Function(str) Int32.Parse(str))