Comma quibbling is a task originally set by Eric Lippert in his blog.



Task

Write a function to generate a string output which is the concatenation of input words from a list/sequence where:

 An input of no words produces the output string of just the two brace characters "{}".
 An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
 An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
 An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".


Test your function with the following series of inputs showing your output here on this page:

 [] # (No input words).
 ["ABC"]
 ["ABC", "DEF"]
 ["ABC", "DEF", "G", "H"]


Note: Assume words are non-empty strings of uppercase characters for this task.




 
' 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
 