kasf - 5 months ago 28x
Vb.net Question

# generate random string

well i know that there are a lot of these threads but im new to vb.net yet i cant edit the sources given to make what i really want
so i want a function that will generate random strings which will contain from 15-32 characters each and each of them will have the following chars ( not all at the same string but some of them ) :
A-Z
a-z
0-9
here is my code so far

``````Functon RandomString()
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim r As New Random
Dim sb As New StringBuilder
For i As Integer = 1 To 8
Dim idx As Integer = r.Next(0, 35)
sb.Append(s.Substring(idx, 1))
Next
return sb.ToString()
End Function
``````

Change the string to include the a-z characters:

``````Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
``````

Change the loop to create a random number of characters:

``````Dim cnt As Integer = r.Next(15, 33)
For i As Integer = 1 To cnt
``````

Note that the upper boundary in the `Next` method is exclusive, so `Next(15, 33)` gives you a value that can range from 15 to 32.

Use the length of the string to pick a character from it:

``````Dim idx As Integer = r.Next(0, s.Length)
``````

As you are going to create random strings, and not a single random string, you should not create the random number generator inside the function. If you call the function twice too close in time, you would end up with the same random string, as the random generator is seeded using the system clock. So, you should send the random generator in to the function:

``````Function RandomString(r As Random)
``````

So, all in all:

``````Function RandomString(r As Random)
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Dim sb As New StringBuilder
Dim cnt As Integer = r.Next(15, 33)
For i As Integer = 1 To cnt
Dim idx As Integer = r.Next(0, s.Length)
sb.Append(s.Substring(idx, 1))
Next
return sb.ToString()
End Function
``````

Usage example:

``````Dim r As New Random
Dim strings As New List<string>()
For i As Integer = 1 To 10