RosettaCodeData/Task/Multisplit/FreeBASIC/multisplit.basic

75 lines
2.0 KiB
Plaintext

' FB 1.05.0 Win64
Sub Split(s As String, sepList() As String, result() As String, removeEmpty As Boolean = False, showSepInfo As Boolean = False)
If s = "" OrElse UBound(sepList) = -1 Then
Redim result(0)
result(0) = s
Return
End If
Dim As Integer i = 0, j, count = 0, empty = 0, length
Dim As Integer position(len(s) + 1)
Dim As Integer sepIndex(1 To len(s))
Dim As Integer sepLength(len(s))
position(0) = 0 : sepLength(0) = 1
While i < Len(s)
For j = lbound(sepList) To ubound(sepList)
length = len(sepList(j))
If length = 0 Then Continue For '' ignore blank separators
If mid(s, i + 1, length) = sepList(j) Then
count += 1
position(count) = i + 1
sepIndex(count) = j
sepLength(count) = length
i += length - 1
Exit For
End If
Next j
i += 1
Wend
Redim result(count)
If count = 0 Then
If showSepInfo Then
Print "No delimiters were found" : Print
End If
result(0) = s
Return
End If
position(count + 1) = len(s) + 1
For i = 1 To count + 1
length = position(i) - position(i - 1) - sepLength(i - 1)
result(i - 1 - empty) = Mid(s, position(i - 1) + sepLength(i - 1), length)
If removeEmpty AndAlso cbool(length = 0) Then empty += 1
Next
If empty > 0 Then Redim Preserve result(count - empty)
If showSepInfo Then
Print "The 1-based indices of the delimiters found are : "
Print
For x As Integer = 1 To count
Print "At index"; position(x), sepList(sepIndex(x))
Next
Print
End If
End Sub
Dim s As String = "a!===b=!=c"
Print "The string to be split is : "; s
Print
Dim a() As String '' to hold results
Dim b(1 To 3) As String = {"==", "!=", "="} '' separators to be used in order of priority (highest first)
split s, b(), a(), False, True '' show separator info
Print "The sub-strings are : "
Print
For i As integer = 0 To ubound(a)
Print Using "##"; i + 1;
Print " : "; a(i)
Next
Print
Print "Press any key to quit"
Sleep