vb.net 生成随机字母数字字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15288692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generate random alphanumeric string
提问by user2024024
I am trying to generate a random code in vb.net like this
我想像这样在 vb.net 中生成一个随机代码
Dim r As New Random
Response.Write(r.Next())
But I want to generate code with 6 digits and should be alphanumeric like thie A12RV1and all codes should be like this.
但我想生成 6 位数字的代码,并且应该是像 thie 一样的字母数字A12RV1,所有代码都应该是这样的。
I have tried vb.net random class but I am unable to do that like as I want. I want to get the alphanumeric code each time when I execute the code. How can i achieve this in vb.net?
我已经尝试过 vb.net 随机课程,但我无法像我想要的那样做。每次执行代码时,我都想获取字母数字代码。我怎样才能在 vb.net 中实现这一点?
回答by SysDragon
Try something like this:
尝试这样的事情:
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
Or you can do the common random string defining the valid caracters:
或者您可以执行定义有效字符的常见随机字符串:
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
回答by Rajaprabhu Aravindasamy
I think this will suits your requirement,
我认为这将满足您的要求,
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
Note:Tested With IDE
笔记:Tested With IDE
EDIT:Modified according to SYSDRAGON's Comment
编辑:Modified according to SYSDRAGON's Comment

