Vb6 How do I make a Random String of 0-9 and a-z of x characters

后端 未结 8 1894
無奈伤痛
無奈伤痛 2021-02-14 03:29

Trying to create a random string, x characters in length using 0-9 and a-z/A-Z and can\'t seem to find a good example, any ideas?

8条回答
  •  遇见更好的自我
    2021-02-14 03:51

    You didn't really say what you were using this for. If you need small strings (<=32,766) I think Joel's function will work fine. However if you need something to generate really large strings, this might be useful. On my system it will do a 1,000,000 char string in 0.33291015625 seconds (yes I know... sledgehammer:)) Also you can parametrize the character set so you don't have to change the code every time you want to do something "special":) :

    Public Function RandomString( _
        ByVal length As Long, _
        Optional charset As String = "abcdefghijklmnopqrstuvwxyz0123456789" _
        ) As String
        Dim chars() As Byte, value() As Byte, chrUprBnd As Long, i As Long
        If length > 0& Then
            Randomize
            chars = charset
            chrUprBnd = Len(charset) - 1&
            length = (length * 2&) - 1&
            ReDim value(length) As Byte
            For i = 0& To length Step 2&
                value(i) = chars(CLng(chrUprBnd * Rnd) * 2&)
            Next
        End If
        RandomString = value
    End Function
    

提交回复
热议问题