Ranhot Ranhot - 6 months ago 53
Vb.net Question

Convert range of number in string to list of integer

I have a string

"2-6,8,10-15,20-23"


I need to have it converted to a fully populated range of numbers in an array as below:

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


Do you have any ideas how to convert it?

Answer

This code should do the trick (the procedure is described in the comments):

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