1

我不明白如何将数字添加到随机字符串中,而不是有时显示类似 3 的字符串,我希望它始终显示 5 字符串,但我不知道该怎么做。

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
4

3 回答 3

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)

第一个参数是字符数,第二个参数是是否需要大写字符(True 或 False)。

于 2013-02-06T07:30:39.967 回答
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
于 2013-02-06T08:30:44.603 回答
0

你需要它是一串数字吗?因为如果不需要,你可以使用 System.IO.Path.GetRandomFileName。此函数为您提供任意长度的随机大写字符串,默认为 8 个字符

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
于 2016-07-13T18:03:32.213 回答