Prashant Prashant - 3 months ago 17
Vb.net Question

Splitting strings of fixed length from dynamic string Vb.net

I am developing an application in VB 2010 wherein I am sending a command to PLC over Serial port and receiving the data from PLC in string.

I have removed unwanted contents of string received from PLC and get the final string in ReturnStr as below:

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 returns string something like 006600D000C9006D0013B003A00014C00349 which I want to split into the set of 4 characters each.

My query is ReturnStr may contain data of indefinite length (in multiples of 4) so how do I go about splitting strings from such string and display value of each substring in labels in the form like this:

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)))

Answer
Dim s = "006600D000C9006D0013B003A00014C00349"
Dim a = From i In Enumerable.Range(0, s.Length \ 4) Select Mid(s, i * 4, 4)

Update

For the updated question

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 ReturnStr.Length \ 4
    labels(i).Text = Val("&h" & Mid(ReturnStr, i * 4, 4))
Next
Comments