VB.NET 读取 PM 文件,提取数据并存入二维数组
VB.NET 读取 PM 文件,提取数据并存入二维数组
本教程将指导您如何使用 VB.NET 读取 PM 文件,并提取特定行的数据,将这些数据存储在一个二维数组中,以便于后续处理。以下是一个示例代码,用于读取 PM 文件,过滤空格和其他符号,并将数字存入二维数组。
代码示例
Imports System.IO
Module Module1
Sub Main()
Dim filePath As String = "C:\path\to\pmfile.txt" ' 替换为你的 PM 文件实际路径
Dim data As New List(Of List(Of Integer))
Using sr As New StreamReader(filePath)
Dim lineCount As Integer = 0
Dim line As String = sr.ReadLine()
While Not String.IsNullOrEmpty(line)
lineCount += 1
If lineCount >= 4 AndAlso (lineCount - 4) Mod 3 = 0 Then
Dim filteredLine As String = FilterLine(line)
If Not String.IsNullOrEmpty(filteredLine) Then
Dim rowData As New List(Of Integer)
For Each value As String In filteredLine.Split(" "c)
If IsNumeric(value) Then
rowData.Add(Convert.ToInt32(value))
End If
Next
data.Add(rowData)
End If
End If
line = sr.ReadLine()
End While
End Using
' 使用二维数据的行和列索引来查找和访问数据
Dim row As Integer = 2
Dim column As Integer = 3
If data.Count > row AndAlso data(row).Count > column Then
Dim value As Integer = data(row)(column)
Console.WriteLine("Value at row {0}, column {1}: {2}", row, column, value)
Else
Console.WriteLine("Invalid row or column index")
End If
Console.ReadLine()
End Sub
Private Function FilterLine(line As String) As String
Dim filteredLine As String = ""
For Each c As Char In line
If Char.IsDigit(c) OrElse c = " "c Then
filteredLine += c
End If
Next
Return filteredLine.Trim()
End Function
End Module
代码说明
- 代码首先定义了 `filePath` 变量,并将其设置为 PM 文件的实际路径。请根据你的文件位置修改此路径。
- 使用 `StreamReader` 读取 PM 文件的内容。
- 循环读取每一行,并使用 `lineCount` 变量记录当前行号。
- 根据条件判断是否需要提取当前行的数据,并将数据存入二维数组 `data` 中。
- 使用 `FilterLine` 函数过滤掉空格和其他符号,只保留数字。
- 最后,使用行和列索引访问二维数组中的特定数据。
注意事项
- 确保 PM 文件的路径正确。
- 如果 PM 文件中的数据使用其他分隔符,请修改代码中的分隔符。
原文地址: https://www.cveoy.top/t/topic/pR4v 著作权归作者所有。请勿转载和采集!