vb.net 中的文本串联

Text concatenation in vb.net

您好,我正在尝试从连续接收的数据中附加文本 我得到的文本长度是 1、2、5、4、1 等。我需要前 5 个字节的数据,我试图将它添加到另一个名为 K 的变量中 如果K的长度达到5的长度,我会把它移动到变量J 并将清除 K

    Dim j = ""
    Dim l = ""
    Dim k As String
Private Sub ReceivedText(ByVal [text] As String) 'input from ReadExisting
    Dim payload As Byte()
    Dim station = TextBox1.Text
    Dim number As String = Regex.Replace([text], "[^0-9]", "")

    If number.Length > 0 Then
        K = K + number
        If K.Length = 5 Then
            j = K
            K = ""
        ElseIf k.Length > 5 Then
            j = K.Substring(0, 5)
            If j.Length = 5 Then
                l = K.Remove(5)
                K = ""
                K = l
            End If
        End If
        If Me.RichTextBox1.InvokeRequired Then
            Dim x As New SetTextCallback(AddressOf ReceivedText)
            Me.Invoke(x, New Object() {(text)})
        Else
            Me.RichTextBox1.Text = K
        End If
    End If

如果变量 K 长度大于 5,我会将第一个变量中的 5 添加到 "J" 并平衡到另一个名为 的变量l 并将其附加到 K,所以我将让第一个变量保持恒定的长度为 5 但是使用上面的代码我无法得到想要的结果,任何建议将不胜感激

在您的代码部分:

        ElseIf k.Length > 5 Then
            j = k.Substring(0, 5)
            If j.Length = 5 Then
                k = ""
                l = k.Remove(0, 5)
                k = l
            End If

删除 k = ""。删除后,您的 l 变量将被正确设置(而不是空白)。这应该可以解决问题。祝你好运。

您应该在函数外部声明 K 变量,以便在函数调用之间保留该值。

Dim K As String = ""

Sub Main
    ' This is to simulate stream of data to pass to ReceivedText function
    Dim arr As String() = {"0", "12", "34567", "8901", "2", "34", "56", "7890", "123", "456"}

    For Each data As String In arr
        ReceivedText(data)
    Next

    Console.WriteLine("End of data stream. Remaining chars (Incomplete) : " & K)

End Sub

Private Sub ReceivedText(ByVal [text] As String)
    Dim number As String = Regex.Replace([text], "[^0-9]", "")

    K &= number ' Append [text] to K

    ' If K length is 5 or more
    If K.Length >= 5 Then
        ' Get the first 5 characters and assign to J
        Dim J As String = K.Substring(0, 5)

        ' I just print the 5-char value (J) to console.
        Console.WriteLine("Completed text (5 chars) : " & J)

        ' Remove the first 5 characters from K
        K = K.Remove(0, 5)
    End If
End Sub

我像上面那样简化了你的代码。

输出

Completed text (5 chars) : 01234
Completed text (5 chars) : 56789
Completed text (5 chars) : 01234
Completed text (5 chars) : 56789
Completed text (5 chars) : 01234
End of data stream. Remaining chars (Incomplete) : 56

上面的Remaining chars不是K中剩余的字符数,而是文本56。正如您在 arr 最后一个数组项中看到的那样,我故意在数据流中放置了额外的字符,因此它们并不是完全以 5 个为一组。