生成随机字母数字字符串

时间:2013-03-08 07:17:29

标签: vb.net

我想在vb.net中生成一个像这样的随机代码

  Dim r As New Random
        Response.Write(r.Next())

但我想生成6位数的代码,并且应该像thie A12RV1一样使用字母数字,所有代码应该是这样的。

我已经尝试过vb.net随机类,但我无法像我想的那样做。我希望每次执行代码时都能获得字母数字代码。我怎样才能在vb.net中实现这一目标?

2 个答案:

答案 0 :(得分:4)

尝试这样的事情:

Public Function GetRandomString(ByVal iLength As Integer) As String
    Dim sResult As String = ""
    Dim rdm As New Random()

    For i As Integer = 1 To iLength
        sResult &= ChrW(rdm.Next(32, 126))
    Next

    Return sResult
End Function

或者您可以使用定义有效字符的公共随机字符串:

Public Function GenerateRandomString(ByRef iLength As Integer) As String
    Dim rdm As New Random()
    Dim allowChrs() As Char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ0123456789".ToCharArray()
    Dim sResult As String = ""

    For i As Integer = 0 To iLength - 1
        sResult += allowChrs(rdm.Next(0, allowChrs.Length))
    Next

    Return sResult
End Function

答案 1 :(得分:1)

我认为这符合您的要求,

 Private sub GenerateString()

 Dim xCharArray() As Char = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray
 Dim xNoArray() As Char = "0123456789".ToCharArray
 Dim xGenerator As System.Random = New System.Random()
 Dim xStr As String = String.Empty

        While xStr.Length < 6

            If xGenerator.Next(0, 2) = 0 Then
                xStr &= xCharArray(xGenerator.Next(0, xCharArray.Length))
            Else
                xStr &= xNoArray(xGenerator.Next(0, xNoArray.Length))
            End If

        End While

        MsgBox(xStr)

 End Sub

注意: Tested With IDE

编辑: Modified according to SYSDRAGON's Comment