RosettaCodeData/Task/Range-expansion/FreeBASIC/range-expansion.basic

76 lines
1.8 KiB
Plaintext

' FB 1.05.0 Win64
Sub split (s As Const String, sepList As Const String, result() As String)
If s = "" OrElse sepList = "" Then
Redim result(0)
result(0) = s
Return
End If
Dim As Integer i, j, count = 0, empty = 0, length
Dim As Integer position(Len(s) + 1)
position(0) = 0
For i = 0 To len(s) - 1
For j = 0 to Len(sepList) - 1
If s[i] = sepList[j] Then
count += 1
position(count) = i + 1
End If
Next j
Next i
Redim result(count)
If count = 0 Then
result(0) = s
Return
End If
position(count + 1) = len(s) + 1
For i = 1 To count + 1
length = position(i) - position(i - 1) - 1
result(i - 1) = Mid(s, position(i - 1) + 1, length)
Next
End Sub
Function expandRange(s As Const String) As String
If s = "" Then Return ""
Dim b() As String
Dim c() As String
Dim result As String = ""
Dim As Integer start = 0, finish = 0, length
split s, ",", b()
For i As Integer = LBound(b) To UBound(b)
split b(i), "-", c()
length = UBound(c) - LBound(c) + 1
If length = 1 Then
start = ValLng(c(LBound(c)))
finish = start
ElseIf length = 2 Then
If Left(b(i), 1) = "-" Then
start = -ValLng(c(UBound(c)))
finish = start
Else
start = ValLng(c(LBound(c)))
finish = ValLng(c(UBound(c)))
End If
ElseIf length = 3 Then
start = -ValLng(c(LBound(c) + 1))
finish = ValLng(c(UBound(c)))
Else
start = -ValLng(c(LBound(c) + 1))
finish = -ValLng(c(UBound(c)))
End If
For j As Integer = start To finish
result += Str(j) + ", "
Next j
Next i
Return Left(result, Len(result) - 2) '' get rid of final ", "
End Function
Dim s As String = "-6,-3--1,3-5,7-11,14,15,17-20"
Print expandRange(s)
Print
Print "Press any key to quit"
Sleep