Разделение строки не работает с файлом в стиле CSV - PullRequest
0 голосов
/ 19 мая 2018

У меня есть текстовый файл с такими данными:

enter image description here

Я хочу разделить каждое слово в массив, например:
В строке 1:
""
""
""
"Этот ПК"
"VGA"
1.000
7.000

Изначально я использовал .Split (""),но это будет отделять слово "этот компьютер".Как мне решить эту проблему?

Sub Main()
    Try

        Using sr As New StreamReader("ReadFile.txt")
            Dim line As String

            Do
                line = sr.ReadLine()
                If Not (line Is Nothing) Then



                    Dim wordArr As String() = line.Split(" ")


                    For Each item As String In wordArr
                        'Debug.Write(item & " ")
                        'Show result every item
                    Next

                End If
            Loop Until line Is Nothing
        End Using
    Catch e As Exception
        Console.WriteLine("The file could not be read:")
        Console.WriteLine(e.Message)
    End Try
End Sub

1 Ответ

0 голосов
/ 19 мая 2018

Вот пример кода, в котором используется синтаксический анализатор текстового поля, чтобы сделать то, что вам нужно.

    Using tfp As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\Users\Charlie\Documents\Test.txt")
        'set the field type to delimited
        tfp.TextFieldType = FileIO.FieldType.Delimited
        'set the delimiter to a space
        tfp.Delimiters = New String() {" "}
        'create a string array to hold the fields
        Dim currentRow As String()

        While Not tfp.EndOfData
            'call ReadFields to fill the string array
            currentRow = tfp.ReadFields()
            'here we're just looping through the row to show the individual fields
            For Each field As String In currentRow
                MsgBox(field)
            Next
        End While
    End Using

Результат с данными вашего примера покажет:

пустая строка
пустая строка
пустая строка
Этот ПК
VGA
1.000
7.000

Они также могут быть получены, как и любой массив.Например, если вы хотите получить «Этот компьютер», вы должны использовать currentRow (3).

...