VB中的随机字符串

时间:2010-08-28 21:45:51

标签: vb.net random

我需要为我的应用程序生成大量随机2个字符的字符串。这是一个VB控制台应用程序。基本上我对随机字符串的尝试是:

  Private Function GenerateRandomString(ByVal intLenghtOfString As Integer) As String
    'Create a new StrinBuilder that would hold the random string.
    Dim randomString As New StringBuilder
    'Create a new instance of the class Random
    Dim randomNumber As Random = New Random
    'Create a variable to hold the generated charater.
    Dim appendedChar As Char
    'Create a loop that would iterate from 0 to the specified value of intLenghtOfString
    For i As Integer = 0 To intLenghtOfString
      'Generate the char and assign it to appendedChar
      appendedChar = Convert.ToChar(Convert.ToInt32(26 * randomNumber.NextDouble()) + 65)
      'Append appendedChar to randomString
      randomString.Append(appendedChar)
    Next
    'Convert randomString to String and return the result.
    Return randomString.ToString()
  End Function

AND THIS:

  Private Function RandomStringGenerator(ByVal intLen As Integer) As String

    Dim r As New Random()

    Dim i As Integer

    Dim strTemp As String = ""

    For i = 0 To intLen

      strTemp = strTemp & Chr(Int((26 * r.NextDouble()) + 65))

    Next

    Return r.Next

  End Function

但是在运行时,它会显示如下内容:

SR  
SR  
SR  
SR  
SR  
SR  
SR  
SR  
SR  
SR  
BR  
BR  
BR  
BR  
BR  
BR  
BR  
KR  
KR  
KR  
KR

等等。

发生了什么事?我以为我很久以前就能做random.Next

2 个答案:

答案 0 :(得分:1)

我之前遇到过与Random对象类似的问题。问题是,当您实例化Random时,它的默认种子值是自Windows启动以来的毫秒数。而且,由于您在几毫秒内生成随机字符,因此最终会得到相同的种子数。

相反,您应该创建一个共享随机对象,而不是在每次调用时实例化一个新对象。

答案 1 :(得分:0)

在另一个论坛中,我回答了类似的问题,并提出了可用于解决问题的通用功能。它包括一个度量标准,可以检查该度量标准以查看生成的字符是否存在偏差。

Dim charUC As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Dim charLC As String = charUC.ToLower
Dim charNUM As String = "0123456789"
Dim charSPEC As String = "``!@#$%^&*()-_=+[{]}\|;:',<.>/?" & ControlChars.Quote
Dim charCounts As New Dictionary(Of Char, Integer)
Dim PRNG As New Random 'note - defined at class level

Private Function GetRandChars(ByVal numChars As Integer, _
                              Optional ByVal includeUpperCase As Boolean = False, _
                              Optional ByVal includeLowerCase As Boolean = False, _
                              Optional ByVal includeNumbers As Boolean = False, _
                              Optional ByVal includeSpecial As Boolean = False) As String

    If numChars <= 0 Then Throw New ArgumentException 'must specify valid character count

    Dim includeSel As New System.Text.StringBuilder 'contains set of characters

    If includeUpperCase Then includeSel.Append(charUC) 'UC to set
    If includeLowerCase Then includeSel.Append(charLC) 'LC to set
    If includeNumbers Then includeSel.Append(charNUM) 'numbers to set
    If includeSpecial Then includeSel.Append(charSPEC) 'specials to set

    If includeSel.Length = 0 Then Throw New ArgumentException 'must tell function at least one include

    Dim rv As New System.Text.StringBuilder 'return value
    'generate specified number of characters
    For ct As Integer = 1 To numChars
        Dim chSel As Char = includeSel(PRNG.Next(includeSel.Length)) 'select random character
        rv.Append(chSel)
        'do counts
        If charCounts.ContainsKey(chSel) Then
            charCounts(chSel) += 1
        Else
            charCounts.Add(chSel, 1)
        End If
    Next
    Return rv.ToString 'return the random string
End Function