VB.NET - Reading a text file containing tab-separated integers/doubles and storing them in arrays

前端 未结 1 1138
别那么骄傲
别那么骄傲 2021-01-20 12:31

I have a text file containing tab-seperated integers and doubles, e.g.:

5[TAB]0.3[TAB]2.9[TAB]61[TAB]110
8[TAB]1.1[TAB]5.2[TAB]13[TAB]45
1[TAB]0.8[TAB]1.4[TA         


        
相关标签:
1条回答
  • 2021-01-20 13:06

    If it's ok to use a list of lists instead of a list of arrays, you can just do this:

    Private Function LoadFile(ByVal filePath As String) As List(Of List(Of Double))
        Dim records As New List(Of List(Of Double))()
        For Each line As String In File.ReadAllLines(filePath)
            Dim values As New List(Of Double)()
            For Each field As String In line.Split(New String() {ControlChars.Tab}, StringSplitOptions.None)
                values.Add(Double.Parse(field))
            Next
            records.Add(values)
        Next
        Return records
    End Function
    

    Or, if it must be a list of arrays, you could do this:

    Private Function LoadFileToArrays(ByVal filePath As String) As List(Of Double())
        Dim records As New List(Of Double())()
        For Each line As String In File.ReadAllLines(filePath)
            Dim values As New List(Of Double)()
            For Each field As String In line.Split(New String() {ControlChars.Tab}, StringSplitOptions.None)
                values.Add(Double.Parse(field))
            Next
            records.Add(values.ToArray())
        Next
        Return records
    End Function
    

    If you need an array of arrays, you could just return records.ToArray(), instead, in that last example. I did not add any code to handle invalid or empty field values, because it wasn't clear, in your question, how you would want to handle those. So, you'll want to add code to handle that appropriately, otherwise, this code will throw an exception in such cases.

    0 讨论(0)
提交回复
热议问题