在vb.net中将文本文件转换为2d数组

时间:2010-10-31 02:09:22

标签: vb.net arrays text-files

我有一个像

这样的文本文件
11111
10001
10001
11111

我需要把它读成2d整数数组 我已经有了读取文件的代码

 Dim fullpath = "Path to File"
 Dim objReader As StreamReader
 objReader = New StreamReader(fullpath)

但我不知道在那之后该怎么做。 我知道这很简单但我现在无法想到它-_-

1 个答案:

答案 0 :(得分:2)

我假设2d数组是将每个单独的数字存储在每一行中。还假设我们只有4行,每行5个数字。 (不要假设这一点,除非你知道它的强制性 - 否则计算必要的大小并重新整理数组)

    Dim myArray(4, 5) As Integer, y As Integer = 0, x As Integer = 0
    Dim fullpath = "Path to File"

    Using sr As StreamReader = New StreamReader(fullpath )
            Do While sr.Peek() >= 0
                   For Each c As Char In sr.ReadLine
                       Try
                           myArray(x, y) = Integer.Parse(c)
                       Catch ex As Exception 'i assume this is the only possible error, but we could be out of bounds due to assuming the actual size of the file/line... catch specific exceptions as necessary'
                           Console.WriteLine(String.Format("Error converting {0} to an integer.", c))
                       End Try
                       y += 1
                   Next
                   x += 1
                   y = 0
            Loop
       End Using