首页 > 解决方案 > 从字符串中获取数字

问题描述

我对使用 Visual Basic 进行编程非常陌生。我正在使用 vb.net 打开一个文本文件。我目前有一个程序可以逐行读取文本文件并将每一行添加到一个数组中。

 Private Function Read_GCode() As ArrayList
    Dim objReader As New System.IO.StreamReader(FILE_NAME)
    Dim TextLine As New ArrayList
    Do While objReader.Peek() <> -1
        TextLine.Add(objReader.ReadLine())
    Loop
    Return TextLine
End Function

我的文本文件会有这样的东西

(* 形状编号: 0 *)

G0 X2999.948 Y1771.567

M3 M8

G0 Z 0.000

G1 Z 0.000

F400

G1 X2999.948 Y 771.567

F0

G1 Z 0.000

G0 Z 0.000

M9 M5

G0 X 0.000 Y 0.000

M2(程序结束)

下一步是编写一个函数来获取每一行的数字。只需要以“G”开头的行。如何从字符串中提取数字?

标签: stringvb.nettextnumbers

解决方案


要读取文本文件,您可以使用File.ReadAllLines它将返回一个行数组。为了解析这些行,我使用了各种String方法并向GData对象添加了属性。最后结果显示在一个 in 中DataGridView

Private GDataList As New List(Of GData)
Private Sub OPCode()
    Dim lines = File.ReadAllLines("G Code.txt")
    For Each line In lines
        If line.StartsWith("G") Then
            GDataList.Add(ParseG(line))
        End If
    Next
    DataGridView1.DataSource = GDataList
End Sub

Private Function ParseG(input As String) As GData
    Dim g As New GData
    Dim words = input.Split(" "c)
    Dim NextWordIndex As Integer
    g.GValue = CInt(words(0).Trim("G"c))
    If words(1).StartsWith("X") Then
        If words(1).Length > 1 Then
            g.XValue = CDbl(words(1).Trim("X"c))
            NextWordIndex = 2
        Else
            g.XValue = CDbl(words(2))
            NextWordIndex = 3
        End If
        If words(NextWordIndex).StartsWith("Y") Then
            If words(NextWordIndex).Length > 1 Then
                g.YValue = CDbl(words(NextWordIndex).Trim("Y"c))
            Else
                g.YValue = CDbl(words(NextWordIndex + 1))
            End If
        End If
    ElseIf words(1).StartsWith("Z") Then
        If words(1).Length > 1 Then
            g.ZValue = CDbl(words(1).Trim("Z"c))
        Else
            g.ZValue = CDbl(words(2))
        End If
    End If
    Return g
End Function

Public Class GData
    Public Property GValue As Integer
    Public Property XValue As Double
    Public Property YValue As Double
    Public Property ZValue As Double
End Class

推荐阅读