如何从列表中打印3个字母单词,这些单词取自分组数组VB

时间:2016-12-06 10:29:52

标签: arrays vb.net list printing

我正在尝试打印包含数组中3个字母单词的列表的内容。代码有效但它会多次打印列表,我不确定为什么。有人可以帮忙吗?我正在使用频率分析构建一个解密软件,根据我的老师,这一步是关键部分。我正在使用Visual Studio中的Windows窗体应用程序。下面是代码及其结果。

Private Sub threeLetterWordButton_Click(sender As Object,e As EventArgs)处理threeLetterWordButton.Click

    freqTextBox.Show()

    Dim threeWordList As New List(Of String)
    Dim encryptedText As String = encryptionInput.Text
    Dim encryptedArrary() As String = Split(encryptedText)

    For Each item In encryptedArrary

        For i = 0 To encryptedArrary.GetUpperBound(0)

            If encryptedArrary(i).Length = 3 Then

                threeWordList.Add(encryptedArrary(i))

                For Each j In threeWordList

                    freqTextBox.Text = freqTextBox.Text & j & " "

                Next

            End If

        Next

    Next

End Sub

结束班

Here is the result of the code

2 个答案:

答案 0 :(得分:2)

你不需要3个循环。此代码将使用以下代码执行:

For Each item In encryptedArrary
        If item.Length = 3 Then
            threeWordList.Add(item)
            freqTextBox.Text = freqTextBox.Text & item & " "
        End If
Next

答案 1 :(得分:2)

扩展前面的答案,你可以将代码检查的长度直接减少到循环声明中,如下所示:

    For Each item In encryptedArrary.Where(Function(x) x.Length = 3)
        threeWordList.Add(item)
        freqTextBox.Text = freqTextBox.Text & item & " "
    Next

这样,您可以在循环开始之前提取3个长度的项目,从而减少迭代次数