0

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)))
Prashant
  • 93
  • 9
  • 5
    There are a [few](http://stackoverflow.com/questions/8774392/how-to-split-a-string-by-x-amount-of-characters) [examples](http://stackoverflow.com/questions/7376987/how-to-split-a-string-into-a-fixed-length-string-array) [in](http://stackoverflow.com/questions/30385540/how-do-i-split-a-string-every-7th-charecter-in-vb?noredirect=1&lq=1) the site. – the_lotus Aug 05 '16 at 12:39

1 Answers1

0
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 labels.Length - 1
    labels(i).Text = Val("&h" & Mid(ReturnStr, i * 4, 4))
Next
Slai
  • 22,144
  • 5
  • 45
  • 53