生成随机字符串数组

时间:2015-08-21 15:39:57

标签: vb.net

我正在尝试构建一个随机生成的特定长度字符串的静态数组。我基于here到目前为止的基础,但数组中的每个索引都有相同的字符串,而不是不同的字符串。我做错了什么?

Dim Target As String
 Target = InputBox("Input target string")

  Dim StringArray(10) As String
        For i = 1 To 10
            StringArray(i) = GenerateString(Len(Target))
            Debug.Print(StringArray(i))
        Next

  Function GenerateString(size As Integer) As String
        Dim LegalCharacters As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        Dim Rnd As New Random()
        Dim Builder As New System.Text.StringBuilder()
        Dim Ch As Char

        For i As Integer = 0 To size - 1
            Ch = LegalCharacters(Rnd.Next(0, LegalCharacters.Length))
            Builder.Append(Ch)
        Next

        Return Builder.ToString()
    End Function

1 个答案:

答案 0 :(得分:1)

这:Dim Rnd As New Random()是发生错误的地方。

当您实例化一个新的Random()时,它将当前时间作为种子。由于您在每次迭代中再次实例化并且所有迭代步骤都在“相同”时间(非常快速连续)发生,因此每个Random()都会生成相同的输出。

您必须在迭代器之前将其实例化一次,并将其作为参数传递给函数,或者您也可以使其成为类的静态属性。

TL; DR:您必须重复使用相同的Random(),而不是为每次迭代创建一个新的。

这应该是正确的代码:

Dim Target As String
Target = InputBox("Input target string")

Dim StringArray(10) As String
    Dim Rnd As New Random()
    For i = 1 To 10
        StringArray(i) = GenerateString(Len(Target), Rnd)
        Debug.Print(StringArray(i))
    Next

 Function GenerateString(size As Integer, Rnd as Random) As String
    Dim LegalCharacters As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    Dim Builder As New System.Text.StringBuilder()
    Dim Ch As Char

    For i As Integer = 0 To size - 1
        Ch = LegalCharacters(Rnd.Next(0, LegalCharacters.Length))
        Builder.Append(Ch)
    Next

    Return Builder.ToString()
End Function