我不明白如何在随机字符串中添加数字,而不是有时显示类似3的字符串,我希望它总是显示一个5的字符串,我不知道如何做到这一点。< / p>
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim rndnumber As Random
Dim number As Integer
rndnumber = New Random
number = rndnumber.Next(1, 80000)
TextBox1.Text = number.ToString
End Sub
答案 0 :(得分:3)
您可以使用此功能创建随机字符串:
Public Function GenerateRandomString(ByRef len As Integer, ByRef upper As Boolean) As String
Dim rand As New Random()
Dim allowableChars() As Char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ0123456789".ToCharArray()
Dim final As String = String.Empty
For i As Integer = 0 To len - 1
final += allowableChars(rand.Next(allowableChars.Length - 1))
Next
Return IIf(upper, final.ToUpper(), final)
End Function
您可以像这样调用此函数:
GenerateRandomString(5, False)
第一个参数是字符数,第二个参数是否需要大写字符(真或假)。
答案 1 :(得分:1)
这将生成长度为5的随机字符串编号:
final = rdm.Next(0, 100000).ToString("00000")
此函数生成任意长度的随机字符串:
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
答案 2 :(得分:0)
你需要它是一串数字?,因为如果没有,你可以使用System.IO.Path.GetRandomFileName。此函数为您提供任意长度的随机大写字符串,默认为八个字符
Public Function GetRandomString(Optional ByVal iLength As Integer = 8) As String
Dim sPath, SResult As String
sPath = ""
Do
sPath = sPath + System.IO.Path.GetRandomFileName.Replace(".", "")
Loop Until sPath.Length > iLength
SResult = sPath.Substring(0, iLength)
Return SResult.ToUpper
End Function