开发者

Split when a character is found ( txt not delimited) using VB.net

开发者 https://www.devze.com 2023-02-25 04:43 出处:网络
I am trying to populate a datagrid from a .txt file. I managed to do it wit开发者_如何学Goh the split function Split(sr.ReadLine, \" \") when I have all the rows identical with only one space, but the

I am trying to populate a datagrid from a .txt file. I managed to do it wit开发者_如何学Goh the split function Split(sr.ReadLine, " ") when I have all the rows identical with only one space, but the problem I have is that the txt file is not delimited and the "spaces" varies some time. This is a sample of my data:

Col1  Col2 Col3
1      Mary Yes
1234   John Yes
999    Leo No

So my question is how to delimit or split the line based when it finds the next character and ignore the empty spaces. This is the code I have.

OpenFileDialog1.Filter = "Text File|*.txt"
    OpenFileDialog1.Title = "Open File..."
    OpenFileDialog1.FileName = "test"

    If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
        Dim sr As System.IO.StreamReader = New System.IO.StreamReader(OpenFileDialog1.FileName)
        Dim srlineitems() As String
        srlineitems = Split(sr.ReadLine, " ")

        Dim DT As New DataTable
        DT.Columns.Add("Col1")
        DT.Columns.Add("Col2")
        DT.Columns.Add("Col3")
        DT.Columns.Add("Col4")

        DataGridView1.DataSource = DT

        Dim Lines() As String = System.IO.File.ReadAllLines(OpenFileDialog1.FileName)

        For Each Line As String In Lines
            Dim ItemsOf() As String = Split(Line, " ")
            Dim NRow As String() = {ItemsOf(0), ItemsOf(1), ItemsOf(2), ItemsOf(3)}

            DT.Rows.Add(NRow)

        Next Line


    End If  

Any help is appreciated


Try the .Net String.Split method instead, it has a RemoveEmptyEntries option.

ItemsOf = Line.Split(New String() {" "},
    StringSplitOptions.RemoveEmptyEntries)
0

精彩评论

暂无评论...
验证码 换一张
取 消