简体   繁体   English

如何在VB.Net中生成7位随机数/特殊字符串?

[英]How to generate and 7-digit random number/special character string in VB.Net?

在VB.Net中,如何在按钮单击事件的文本框中生成7位随机数和特殊字符串?

Put the characters you want in a string and pick from that: 将所需的字符放入字符串中,然后从中选择:

Dim chars As String = "0123456789abcdefghijklmnopqrstuvwxyz!#%&()?+-;:"
Dim word As Char() = New Char(6)
Dim rnd As New Random()
For i As Integer = 0 To word.Length - 1
  word(i) = chars.Chars(rnd.Next(chars.Length))
Next
TheTextBox.Text = New String(word)

here is a light weight version i use: 这是我使用的轻量级版本:

Protected Function GetRandomPass() As String
    Dim pass As String = String.Empty
    Dim AllowedChars() As String = {"ABCDEFGHJKLMNPQRSTWXYZ", "abcdefghjklmnpqrstwxyz", "0123456789"}
    Dim rnd = New Random()
    While pass.Length < 10
        Dim rndSet As Integer = rnd.Next(0, AllowedChars.Length)
        pass &= AllowedChars(rndSet).Substring(rnd.Next(0, AllowedChars(rndSet).Length), 1)
    End While
    Return pass
End Function

it chooses a random index of the AllowedChars() array and then chooses a random character in that index using the substring property and appends it to the pass string when the string reaches the defined length it returns the randomly generated password. 它选择AllowedChars()数组的随机索引,然后使用substring属性在该索引中选择一个随机字符,并在字符串达到定义的长度时将其附加到pass字符串中,从而返回随机生成的密码。

this way you can keep your character types separate and also have the ability to add more items to the AllowedChars() array with out editing the rest of the function 这样,您可以使字符类型保持分离,还可以在不编辑其余函数的情况下将更多项添加到AllowedChars()数组中。

I know you could do this with just a plain string and get a random substring out of it but i prefer to see the differences between UPPER, lowercase, and num3r1c/($pec|@|_) characters. 我知道您可以只用一个纯字符串来执行此操作,并从中获得一个随机substring ,但是我更喜欢看到UPPER,小写和num3r1c /($ pec | @ | _)字符之间的区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM