none
VB.NET Generate a random string of numbers and letters

Answers


  • Here is the basic idea.  If you want upper and lower case letters, then add the lower case letters to the string s.
     
        Sub Main()
            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
            Console.WriteLine(sb.ToString())
            Console.ReadKey()
        End Sub
     
     

    --
    Mike
    • Marked as answer by Xakepa Saturday, July 17, 2010 4:03 PM
    Saturday, July 17, 2010 4:01 PM

All replies


  • Here is the basic idea.  If you want upper and lower case letters, then add the lower case letters to the string s.
     
        Sub Main()
            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
            Console.WriteLine(sb.ToString())
            Console.ReadKey()
        End Sub
     
     

    --
    Mike
    • Marked as answer by Xakepa Saturday, July 17, 2010 4:03 PM
    Saturday, July 17, 2010 4:01 PM
  • How can I implement this into a Windows Froms Application. I need it as a dim value.

    Saturday, July 17, 2010 4:04 PM
  • uppercase, lowercase or both?

    can letters/numbers repeat or not?

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim Letters As New List(Of Integer)
        'add ASCII codes for numbers
        For i As Integer = 48 To 57
          Letters.Add(i)
        Next
        'lowercase letters
        For i As Integer = 97 To 122
          Letters.Add(i)
        Next
        'uppercase letters
        For i As Integer = 65 To 90
          Letters.Add(i)
        Next
        'select 8 random integers from number of items in Letters
        'then convert those random integers to characters and
        'add each to a string and display in Textbox
        Dim Rnd As New Random
        Dim SB As New System.Text.StringBuilder
        Dim Temp As Integer
        For count As Integer = 1 To 8
          Temp = Rnd.Next(0, Letters.Count)
          SB.Append(Chr(Letters(Temp)))
        Next
    
        Label1.Text = SB.ToString
      End Sub
    
      Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Label1.Font = New Font("Arial", 14)
      End Sub
    
    Saturday, July 17, 2010 4:07 PM

  • The code would be the same, except I guess you want a function:
     
    Functon GeneratePassword()
            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
     

    --
    Mike
    Saturday, July 17, 2010 4:10 PM
  • Here is a function I just wrote that will do this.  You can update the string array so that it will only use characters you want.  You can also specify the length when calling it:

    In your case from a WinForm, you could see a message box of the values it creates with this code:

        MsgBox(RandomString(8))
    
     ''' <summary>
     ''' Returns a random string of the specified length. 
     ''' </summary>
     ''' <param name="length"></param>
     ''' <returns></returns>
     ''' <remarks>
     ''' All supported characters are contained in the chars() string array. Characters can be added or removed from this array to
     ''' add or remove them from inclusion when the random string is created.
     ''' bpell
     ''' </remarks>
     Public Function RandomString(ByVal length As Integer) As String
      Dim sb As New System.Text.StringBuilder
      Dim chars() As String = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", _
             "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "X", _
             "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}
      Dim upperBound As Integer = UBound(chars)
    
      For x As Integer = 1 To length
       sb.Append(chars(Int(Rnd() * upperBound)))
      Next
    
      Return sb.ToString
    
     End Function
    
    Saturday, July 17, 2010 4:11 PM
  • jwavila's code shows me I goofed on the value using the random function.  Use the following line to find idx in my code:
     
    dim idx as integer = r.Next(0, s.Length)

     

    --
    Mike
    Saturday, July 17, 2010 4:12 PM
  • Let me add this also: If you want it to be truly unique (or veritably no possibility of there being another one just like it), embed the date and time (to the second) in it. Between that and the random, I can't imagine it not to be unique.
    Saturday, July 17, 2010 4:15 PM
  • Hehe, look at all the answers before I got my post finished. :)  Gotta love the community response time.  :)
    Saturday, July 17, 2010 4:15 PM
  • This is the only one that worked for me. Any idea how to exclude individual numbers and letters?


    Friday, March 29, 2013 11:39 AM
  • Mike, I am just dropping in to let you know that your posting is useful to me. Here is my code:

    '--------------------------------------------------------------------------------------
    ' Class to generate 8-letter string in upper case, generation is by random, uniqueness 
    ' by keeping generated values in a list - scope of uniquness is within object instance.
    '--------------------------------------------------------------------------------------
    
    Imports System.Text
    
    Public Class UniqueRandomString
    
        Dim allocated As List(Of StringBuilder) = New List(Of StringBuilder)
    
        Public Function generate() As String
            Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
            Dim r As Random = New Random
            Dim sb As StringBuilder = New StringBuilder
            Do
                For i As Integer = 1 To 8
                    Dim idx As Integer = r.Next(0, 35) '26 letters + 10 digits
                    sb.Append(s.Substring(idx, 1))
                Next
            Loop Until Not allocated.Contains(sb)
            allocated.Add(sb)
            Return sb.ToString()
        End Function
    
    End Class

    Usage example:

    Dim URS8 as UniqueRandomString = New UniqueRandomString
    Console.WriteLine(URS8.generate())

    Result: Expect to output an 8 letter-wide unique string.

    Note: The string is unique ONLY to the object URS8. That is, repeating calling URS8.generate() will generate a different string until all the permutations had been exausted.

    Further considerations: After a large number of call to URS8.generate() performance will degrade due to growing size of the list. When permutatiions have been exhausted the do-loop will deadlock.



    • Edited by coarist Saturday, June 29, 2013 12:58 AM Correction "for" changed to "do"
    Saturday, June 29, 2013 12:55 AM
  • Here is far much better code that will allow you to not only generate random numbers and letters but also special characters... You type in the beginning how long do you want your password to be and it will take that number and give you the password.... Enjoy the results...

    -------------------------------------------------------------------------------------------------------------------------------

    Public Class frmPassGen

        Private Sub cmdExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdExit.Click
            On Error Resume Next
            ' exit program
            Me.Close()
            End
        End Sub

        Private Sub cmdClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdClear.Click
            On Error Resume Next
            txtPassword.Text = ""
            txtLenPass.Text = ""
            txtLenPass.Focus()
        End Sub

        Private Sub cmdOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdOK.Click
            On Error Resume Next
            Dim Letters As New List(Of Integer)
            'add ASCII Codes for Numbers
            For i As Integer = 48 To 57
                Letters.Add(i)
            Next
            'Lower Case
            For i As Integer = 97 To 122
                Letters.Add(i)
            Next
            'Upper Case
            For i As Integer = 65 To 90
                Letters.Add(i)
            Next
            'Special Characters
            For i As Integer = 33 To 42
                Letters.Add(i)
            Next
            'Select 8 to 12 random integers from number of itesm in Letters
            'Convert those random integers to characters and
            'Add each to string to display in txtPassword.text

            Dim Rnd As New Random
            Dim SB As New System.Text.StringBuilder
            Dim Temp As Integer
            For count As Integer = 1 To Val(txtLenPass.Text)
                
                Temp = Rnd.Next(0, Letters.Count)
                SB.Append(Chr(Letters(Temp)))

            Next
            txtPassword.Text = SB.ToString

        End Sub

    End Class

    Wednesday, August 27, 2014 9:35 PM