我正在閱讀一個 csv 檔案。每行包含一個逗號分隔的字串。我正在嘗試將字串轉換為陣列,以便用新值更新一些字串。我在用
Lines(0) = "test, "The quick brown fox, ran through a log", Another sentence"
words = Lines(0).Split(New Char() {","c})
“The quick brown fox, running through a log”在 words 陣列中創建了 2 個條目
words(0) = "test"
words(1) = ""The quick brown fox"
words(2) = "ran through a log""
words(3) = "Another sentence"
我怎樣才能讓陣列顯示為
words(0) = "test"
words(1) = ""The quick brown fox, ran through a log""
words(2) = "Another sentence"
然后,在更改字串后,將 words 陣列轉換回逗號分隔的字串
newWords = String.Join(",", words.ToArray())
uj5u.com熱心網友回復:
一種方法是替換一些您知道不會在任何地方使用的符號的引號之間的逗號,例如用“|”。拆分完成后,您將 | 放回原處。用逗號。
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
uj5u.com熱心網友回復:
這是丑陋的,但它的作業原理。如果你真的想要,你可以在最終串列中用雙雙引號 ("") 替換單引號。行內解釋。
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/327055.html
上一篇:使用do回圈直到輸入數字的總和
