RosettaCodeData/Task/Comma-quibbling/FreeBASIC/comma-quibbling.basic

59 lines
1.4 KiB
Plaintext

' FB 1.05.0 Win64
Sub Split(s As String, sep As String, result() As String)
Dim As Integer i, j, count = 0
Dim temp As String
Dim As Integer position(Len(s) + 1)
position(0) = 0
For i = 0 To Len(s) - 1
For j = 0 To Len(sep) - 1
If s[i] = sep[j] Then
count += 1
position(count) = i + 1
End If
Next j
Next i
position(count + 1) = Len(s) + 1
Redim result(count)
For i = 1 To count + 1
result(i - 1) = Mid(s, position(i - 1) + 1, position(i) - position(i - 1) - 1)
Next
End Sub
Function CommaQuibble(s As String) As String
Dim i As Integer
Dim As String result
Dim As String words()
s = Trim(s, Any "[]""")
' Now remove internal quotes
Split s, """", words()
s = ""
For i = 0 To UBound(words)
s &= words(i)
Next
' Now split 's' using the comma as separator
Erase words
Split s, ",", words()
' And re-assemble the string in the desired format
result = "{"
For i = 0 To UBound(words)
If i = 0 Then
result &= words(i)
ElseIf i = UBound(words) Then
result &= " and " & words(i)
Else
result &= ", " + words(i)
EndIf
Next
Return result & "}"
End Function
' As 3 of the strings contain embedded quotes these need to be doubled in FB
Print CommaQuibble("[]")
Print CommaQuibble("[""ABC""]")
Print CommaQuibble("[""ABC"",""DEF""]")
Print CommaQuibble("[""ABC"",""DEF"",""G"",""H""]")
Print
Print "Press any key to quit the program"
Sleep