我正在VB 2010中开发一个应用程序,其中我通过串口向PLC发送命令,并以字符串形式从PLC接收数据。
我删除了从PLC收到的不需要的字符串内容,并在 ReturnStr 中获取最终字符串,如下所示:
Dim WriteStr, ChkWrite As String
Dim ReadStr, ReturnStr, ChkRecd, ChkCalc As String
Dim ChkComp As Integer
WriteStr = String.Concat("01", cmd, Add, Points)
ChkWrite = Check(WriteStr)
Try
sp.WriteLine(":" & WriteStr & ChkWrite & vbCr)
ReadStr = sp.ReadLine()
Catch ReadErr As Exception
Return "0"
End Try
ChkRecd = ReadStr.Substring((((CInt("&H" & Points)) * 4) + 7), 2)
ChkCalc = Check(ReadStr.Substring(1, ((Len(ReadStr) - 4))))
ChkComp = String.Compare(ChkRecd, ChkCalc)
If ChkComp <> 0 Then
Return "0"
End If
ReturnStr = (ReadStr.Substring(7)).Remove(CInt("&H" & (Points)) * 4)
Return ReturnStr
ReturnStr 返回类似006600D000C9006D0013B003A00014C00349的字符串,我想将其拆分为每组4个字符。
我的查询 ReturnStr 可能包含无限长度的数据(以4的倍数表示),那么如何从这样的字符串中拆分字符串并以这样的形式显示标签中每个子字符串的值:
lblPt1.Text = CInt("&h" & (ReturnStr.Substring(0, 4)))
lblPt2.Text = CInt("&h" & (ReturnStr.Substring(4, 4)))
lblPt3.Text = CInt("&h" & (ReturnStr.Substring(8, 4)))
lblPt4.Text = CInt("&h" & (ReturnStr.Substring(12, 4)))
lblPt5.Text = CInt("&h" & (ReturnStr.Substring(16, 4)))
lblPt6.Text = CInt("&h" & (ReturnStr.Substring(20, 4)))
lblPt7.Text = CInt("&h" & (ReturnStr.Substring(24, 4)))
lblPt8.Text = CInt("&h" & (ReturnStr.Substring(28, 4)))
答案 0 :(得分:0)
Dim s = "006600D000C9006D0013B003A00014C00349"
Dim a = From i In Enumerable.Range(0, s.Length \ 4) Select Mid(s, i * 4, 4)
<强>更新强>
更新问题
Dim labels = { lblPt1, lblPt2, lblPt3, lblPt4, lblPt5, lblPt6, lblPt7, lblPt8 }
' or query them from Me.Controls.OfType(Of Label) or just use ListBox or better conrol
ReturnStr = ReturnStr.PadRight(labels.Length * 4)
For i = 0 To labels.Length - 1
labels(i).Text = Val("&h" & Mid(ReturnStr, i * 4, 4))
Next