# How to store ranges of numbers separted by comma and hyphen in an array?

I have to store numbers contained in a string into arrays in a special way.
The string contains comma and hyphen.

• The comma-separated numbers should be stored individually
• Numbers separated by a hyphen should be stored as a range of values.

For example, my string is:

``````Reg. No 556002,556010-556013,556039 Cancelled
``````

The array should store the numbers as:

``````(0) 556002   - Single
(1) 556010   ---------|
(2) 556011    Range of
(3) 556012    values
(4) 556013   ---------|
(5) 556039   - Single
``````

I tried the following code:

``````Dim i, str
Dim array() As Char = str.ToCharArray()
Dim rnoarray() As Integer = New Integer() {}
Dim rno = ""
Dim nosta As Boolean
Dim j = 0
str = "Reg. No 556002,556010-556013,556039 Cancelled"
nosta = False
ReDim rnoarray(Len(str) + 2)
For i = 0 To Len(str)-1
If IsNumeric(array(i)) Then
rno = rno & array(i)
nosta = True
Else
If nosta = True Then
rnoarray(j) = Val(rno)
j = j + 1
nosta = False
rno = ""
End If
End If
Next
For x = 0 To j - 1
MessageBox.Show(rnoarray(x))
Next
``````

But the result only includes four numbers:

``````556002
556010
556013
556039
``````

## Solution

Some steps to consider:

• Extract the numbers from the input string, preserving the hyphen when present
• Verify whether one of the parts contains a hyphen:
• In this case, `Split()` the string into two parts
• Convert to `Integer` the two parts
• Take the minimum and the maximum values
• Create a range of numbers between the minimum and maximum values
• Add the range of numbers to a `List(Of Integer)`
• Convert strings that do not contain a hyphen to `Integer`
• Add the converted numbers to a `List(Of Integer)`
``````Imports System.Collections.Generic
Imports System.Linq
Imports System.Text.RegularExpressions

Dim input = "Reg. No 556002,556010-556013,556039 Cancelled"
Dim numbers As New List(Of Integer)

Dim matches = Regex.Matches(input, "d+-*d*").OfType(Of Match)
For Each m As Match In matches
If m.Value.Contains("-") Then
Dim parts = m.Value.Split("-"c).Select(Function(s) Integer.Parse(s)).ToArray()
Dim nStart As Integer = Math.Min(parts(0), parts(1))
Dim nEnd As Integer = Math.Max(parts(0), parts(1))
numbers.AddRange(Enumerable.Range(nStart, nEnd - nStart + 1))
Else
End If
Next
``````

Without Regular Expression (assuming the input string format presented here matches the original):

``````For Each part As String In input.Split(","c)
If part.Contains("-") Then
Dim nValues = part.Split("-"c).Select(Function(s) Integer.Parse(s)).ToArray()
Dim nStart As Integer = Math.Min(nValues(0), nValues(1))
Dim nEnd As Integer = Math.Max(nValues(0), nValues(1))
numbers.AddRange(Enumerable.Range(nStart, nEnd - nStart + 1))
Else
Dim sValue = String.Concat(part.Where(Function(c) Char.IsDigit(c)))
End If
Next
``````

﻿