I am reading through a csv file. Each line contains a comma delimeted string. I am trying to convert the string into an array in order to update a few strings with new values. I am using
Lines(0) = "test, "The quick brown fox, ran through a log", Another sentence"
words = Lines(0).Split(New Char() {","c})
The "The quick brown fox, ran through a log" is creating 2 entries in the words array
words(0) = "test"
words(1) = ""The quick brown fox"
words(2) = "ran through a log""
words(3) = "Another sentence"
how can I get the array to display as
words(0) = "test"
words(1) = ""The quick brown fox, ran through a log""
words(2) = "Another sentence"
I then convert the words array back to a comma delimited string after I made my string changes
newWords = String.Join(",", words.ToArray())
CodePudding user response:
It is ugly but it works. If you really want to you can replace the single quotes with double double quotes ("") in the final list. Explanations in line.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim lst As New List(Of String)
Dim s = "test, 'The quick brown fox, ran through a log', Another sentence"
Dim sb As New StringBuilder
Dim Count As Integer
For Each c In s
If c = ","c OrElse c = " "c Then 'ignore commas and spaces
Continue For
End If
If c = "'"c AndAlso CountIsEven(Count) Then 'beginning quote
lst.Add(sb.ToString) 'add existing string to list
sb.Clear() 'and clear the string builder
sb.Append(c) 'start a new string with the single quote
Count = 1 'increment the counter
Continue For ' go to the next character in the string
ElseIf c = "'"c AndAlso Not CountIsEven(Count) Then 'ending quote (an odd number of single quotes)
sb.Append(c) 'add the single quote to the end of the sb
lst.Add(sb.ToString) 'add to list
sb.Clear() 'clear the sb, always clear after we add to list
Count = 1
Continue For
End If
sb.Append(c) 'the character is not a single quote, comma, or space
Next
lst.Add(sb.ToString) 'Add the last string to the list
For Each s In lst
Debug.Print(s)
Next
End Sub
Private Function CountIsEven(i As Integer) As Boolean
If i Mod 2 = 0 Then
Return True
Else
Return False
End If
End Function
CodePudding user response:
One way is to replace the comma that is between quotation for some symbol that you know you'll not use anywhere, for example with "|". After the splitting is done you replace back the | by comma.
Dim i As Integer
Dim words() As String
Dim bQuoteStart As Boolean = False
Dim sTmp As String = "test, ""The quick brown fox, ran through a log"", Another sentence"
For i = 1 To sTmp.Length
If Mid(sTmp, i, 1) = Chr(34) Then bQuoteStart = Not bQuoteStart
If bQuoteStart AndAlso Mid(sTmp, i, 1) = "," Then sTmp = sTmp.Remove(i - 1, 1).Insert(i - 1, "|")
Next
words = sTmp.Split(New Char() {","c})
For i = 0 To words.Length - 1
MsgBox(words(i).Replace("|", ","))
Next