Results 1 to 10 of 10

Thread: Generate Random String (Letters & Numbers)

  1. #1

    Thread Starter
    Fanatic Member Emcrank's Avatar
    Join Date
    Jan 2009
    Posts
    566

    Generate Random String (Letters & Numbers)

    Here is a Sub to Generate a random string out of the letters A-Z and numbers 0-9, you can add more if you like.
    ADDED: Feature so you cannot get the same string twice. (Even though it is very unlikly)
    VB.NET Code:
    1. Private Sub GenerateString(ByVal Control As Control)
    2.         Dim ListChars As New List(Of String)({"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", _
    3.                               "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", _
    4.                               "u", "v", "w", "x", "y", "z", _
    5.                               "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", _
    6.                               "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", _
    7.                               "U", "V", "W", "X", "Y", "Z", _
    8.                               "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"})
    9.         Dim RandNumb As New Random
    10.         Dim random1 As String = ListChars(RandNumb.Next(0, ListChars.Count - 1))
    11.         Dim random2 As String = ListChars(RandNumb.Next(0, ListChars.Count - 1))
    12.         Dim random3 As String = ListChars(RandNumb.Next(0, ListChars.Count - 1))
    13.         Dim random4 As String = ListChars(RandNumb.Next(0, ListChars.Count - 1))
    14.         Dim random5 As String = ListChars(RandNumb.Next(0, ListChars.Count - 1))
    15.         Dim random6 As String = ListChars(RandNumb.Next(0, ListChars.Count - 1))
    16.         Dim random7 As String = ListChars(RandNumb.Next(0, ListChars.Count - 1))
    17.         Dim random8 As String = ListChars(RandNumb.Next(0, ListChars.Count - 1))
    18.         Dim History As New List(Of String)
    19.         Dim GeneratedString As String = random1 & random2 & random3 & random4 & random5 & random6 & random7 & random8
    20.         If History.Contains(GeneratedString) Then
    21.             Do Until Not History.Contains(GeneratedString)
    22.                 random1 = ListChars(RandNumb.Next(0, ListChars.Count - 1))
    23.                 random2 = ListChars(RandNumb.Next(0, ListChars.Count - 1))
    24.                 random3 = ListChars(RandNumb.Next(0, ListChars.Count - 1))
    25.                 random4 = ListChars(RandNumb.Next(0, ListChars.Count - 1))
    26.                 random5 = ListChars(RandNumb.Next(0, ListChars.Count - 1))
    27.                 random6 = ListChars(RandNumb.Next(0, ListChars.Count - 1))
    28.                 random7 = ListChars(RandNumb.Next(0, ListChars.Count - 1))
    29.                 random8 = ListChars(RandNumb.Next(0, ListChars.Count - 1))
    30.                 GeneratedString = random1 & random2 & random3 & random4 & random5 & random6 & random7 & random8
    31.             Loop
    32.         End If
    33.         Control.Text = GeneratedString
    34.     End Sub
    And to call this sub to put the generated string in a textbox just do,
    VB.NET Code:
    1. GenerateString(TextBox1)

  2. #2

    Re: Generate Random 8 Char String (Letters & Numbers)

    That is a very...interesting way of doing it. However, it's rather long and bulky, not a lot of stuff required. This is a rewrite that I suggest for you:

    Code:
    Imports System.Text
    
    Public Class RandomStringMaker
        Dim ListChars As New List(Of String)
        Dim History As New List(Of String)
        Public Sub New()
            ListChars.Add("a")
            ListChars.Add("b")
            ListChars.Add("c")
            ListChars.Add("d")
            ListChars.Add("e")
            ListChars.Add("f")
            ListChars.Add("g")
            ListChars.Add("h")
            ListChars.Add("i")
            ListChars.Add("j")
            ListChars.Add("k")
            ListChars.Add("l")
            ListChars.Add("m")
            ListChars.Add("n")
            ListChars.Add("o")
            ListChars.Add("p")
            ListChars.Add("q")
            ListChars.Add("r")
            ListChars.Add("s")
            ListChars.Add("t")
            ListChars.Add("u")
            ListChars.Add("v")
            ListChars.Add("w")
            ListChars.Add("x")
            ListChars.Add("y")
            ListChars.Add("z")
            ListChars.Add("1")
            ListChars.Add("2")
            ListChars.Add("3")
            ListChars.Add("4")
            ListChars.Add("5")
            ListChars.Add("6")
            ListChars.Add("7")
            ListChars.Add("8")
            ListChars.Add("9")
        End Sub
        Public Function GenerateString(ByVal length As Integer) As String
            Dim RandNumb As New Random
            Dim StrBld As New StringBuilder
    
            If length > 0 Then
                StrBld.Append(ListChars(RandNumb.Next(0, ListChars.Count - 1)))
                Do Until Not History.Contains(StrBld.ToString) AndAlso StrBld.Length >= length
                    For i As Integer = 1 To length - 1
                        StrBld.Append(ListChars(RandNumb.Next(0, ListChars.Count - 1)))
                    Next
                Loop
                ListChars.Add(StrBld.ToString)
                Return StrBld.ToString
            Else
                Return String.Empty
            End If
        End Function
    
    End Class
    Wrapped in a class too. Take a look at how it's compacted down. It occasionally has a flaw so that's why I had to do the >= length method. It generally speaking won't give much of a problem though. I only had it mess up once.

  3. #3
    Lively Member
    Join Date
    Jul 2009
    Location
    Amsterdam, NY
    Posts
    85

    Re: Generate Random 8 Char String (Letters & Numbers)

    here's what i got (Like formlesstree4, I was going to add an item to make it so you can choose how long the string was), but since he did that, I get to contribute shorter code (somewhat), and the ability to have uppercase letters.

    Code:
    Imports System.Text
    Public Class RandomStringMaker
         Dim ListChars As New List(Of 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", "Z", _
                                  "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"})
         Dim History As New List(Of String)
    
         Public Function GenerateString(ByVal length As Integer) As String
              Dim RandNumb As New Random
              Dim StrBld As New StringBuilder
    
              If length > 0 Then
                   StrBld.Append(ListChars(RandNumb.Next(0, ListChars.Count - 1)))
                   Do Until Not History.Contains(StrBld.ToString) AndAlso StrBld.Length >= length
                        For i As Integer = 1 To length - 1
                             StrBld.Append(ListChars(RandNumb.Next(0, ListChars.Count - 1)))
                        Next
                   Loop
                   ListChars.Add(StrBld.ToString)
                   Return StrBld.ToString
              Else
                   Return String.Empty
              End If
         End Function
    
    End Class
    CodeBank Posts: Base Converter

  4. #4

    Thread Starter
    Fanatic Member Emcrank's Avatar
    Join Date
    Jan 2009
    Posts
    566

    Re: Generate Random 8 Char String (Letters & Numbers)

    Thankyou for this code, it does look better than mine. But shouldn't this bit be History.Add instead of
    Code:
    ListChars.Add(StrBld.ToString)
    Also how do i use it? Because i tried
    Code:
    AliasTB.Text = RandomStringMaker.GenerateString
    but the only thing there when i use the RandomStringMaker constuctor is Equals and ReferenceEquals. Sorry if its noobish question.

  5. #5

    Re: Generate Random 8 Char String (Letters & Numbers)

    Ah yes, it should be History, not ListChars...my mistake.

  6. #6

  7. #7

    Re: Generate Random 8 Char String (Letters & Numbers)

    Dim RMS As New RandomStringMaker
    Dim Str As String = RMS.GenerateString(8) 'Makes a String that's 8 in length.

  8. #8

  9. #9
    Lively Member
    Join Date
    Jul 2009
    Location
    Amsterdam, NY
    Posts
    85

    Re: Generate Random String (Letters & Numbers)

    Here is an update, I was trying to add some optional parameters to adjust how many repeating values are allowed, but I got aggravated so I'm just posting this atm.

    Added a function to add symbols to the list of characters. (and remove)

    here is the full code, with examples of how to use.

    vb.net Code:
    1. Imports System.Text
    2.  
    3. Public Class Form1
    4.  
    5.      Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    6.           Dim str As New RandomStringMaker
    7.           Dim listToAdd As New List(Of String)({"⌐", "½", "¢"}) 'note that you can add "symbols" that are more than one character long, be careful doing this
    8.           'because it might mess with the length of the string, and I havn't tested it throughly
    9.           Dim listToRemove As New List(Of String)({"A", "z"}) 'removes "A" and "z" from the list of characters.
    10.  
    11.           str.EnableSymbols() ' enables the 30 default symbols
    12.           str.RemoveCharacters(listToRemove.ToList) ' removes A and z from the list of characters we build our string from.
    13.           str.AddCharacters(listToAdd.ToList) ' adds ¢, ½, ⌐ to the list of characters we build our string from.
    14.           ListBox1.Items.Add(str.GenerateString(5)) ' creates a string 5 characters long.
    15.  
    16.           str.DisableSymbols() 'removes the default 30 symbols, it is NOT neccessary to call this, and how i have it now is USELESS, but just incase ya needed the example it is here.
    17.  
    18.      End Sub
    19. End Class
    20.  
    21.  
    22. Public Class RandomStringMaker
    23.      '30 symbols that are acceptable in passwords according to this site: http://publib.boulder.ibm.com/infocenter/tivihelp/v4r1/index.jsp?topic=/com.ibm.tpc_V33.doc/fqz0_r_valid_userids_and_passwords.html
    24.      Dim _Symbols As New List(Of String)({"`", "~", "@", "#", "%", "^", "&", "*", "(", ")", _
    25.                                       "-", "_", "=", "+", "[", "]", "{", "}", "\", "|", _
    26.                                       ";", ":", "'", """", ",", ".", "<", ">", "/", "?"})
    27.  
    28.      'list of A-Z,a-z, 0-9 / characters we will use to build our string.
    29.      Dim ListChars As New List(Of String)({"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", _
    30.                               "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", _
    31.                               "u", "v", "w", "x", "y", "z", _
    32.                               "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", _
    33.                               "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", _
    34.                               "U", "V", "W", "X", "Y", "Z", _
    35.                               "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"})
    36.  
    37.      Dim History As New List(Of String) 'holds all the strings we generate so we do not get a double.
    38.  
    39.      'leaving the next 2 subs public just incase you want to add your own symbols.
    40.      'remove certain characters from the list we use to build our strings
    41.      Public Sub RemoveCharacters(ByVal characters As List(Of String))
    42.           For i As Integer = 0 To characters.Count - 1
    43.                ListChars.Remove(characters(i).ToString)
    44.           Next
    45.      End Sub
    46.  
    47.      'add certain characters from the list we use to build our strings
    48.      Public Sub AddCharacters(ByVal characters As List(Of String))
    49.           ListChars.AddRange(characters.ToList)
    50.      End Sub
    51.  
    52.      'adds the 30 acceptable symbols to the list of characters with which we will build our string from.
    53.      Public Sub EnableSymbols()
    54.           AddCharacters(_Symbols.ToList)
    55.      End Sub
    56.  
    57.      'removes the 30 acceptable symbols from the list of the characters used to build our strings.
    58.      Public Sub DisableSymbols()
    59.           RemoveCharacters(_Symbols.ToList)
    60.      End Sub
    61.  
    62.      Public Function GenerateString(ByVal length As Integer) As String
    63.           Dim RandNumb As New Random
    64.           Dim StrBld As New StringBuilder
    65.  
    66.           If length > 0 Then
    67.                Do Until Not History.Contains(StrBld.ToString) AndAlso StrBld.Length >= length
    68.                     For i As Integer = 0 To length - 1
    69.                          StrBld.Append(ListChars(RandNumb.Next(0, ListChars.Count - 1)))
    70.                     Next
    71.                Loop
    72.  
    73.                History.Add(StrBld.ToString)
    74.                Return StrBld.ToString
    75.           Else
    76.                Return String.Empty
    77.           End If
    78.      End Function
    79.  
    80.  
    81. End Class


    for the sake of your copy/paste:
    Code:
    Imports System.Text
    
    Public Class Form1
    
         Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
              Dim str As New RandomStringMaker
              Dim listToAdd As New List(Of String)({"⌐", "½", "¢"}) 'note that you can add "symbols" that are more than one character long, be careful doing this
              'because it might mess with the length of the string, and I havn't tested it throughly
              Dim listToRemove As New List(Of String)({"A", "z"}) 'removes "A" and "z" from the list of characters.
    
              str.EnableSymbols() ' enables the 30 default symbols
              str.RemoveCharacters(listToRemove.ToList) ' removes A and z from the list of characters we build our string from.
              str.AddCharacters(listToAdd.ToList) ' adds ¢, ½, ⌐ to the list of characters we build our string from.
              ListBox1.Items.Add(str.GenerateString(5)) ' creates a string 5 characters long.
    
              str.DisableSymbols() 'removes the default 30 symbols, it is NOT neccessary to call this, and how i have it now is USELESS, but just incase ya needed the example it is here.
    
         End Sub
    End Class
    
    
    Public Class RandomStringMaker
         '30 symbols that are acceptable in passwords according to this site: http://publib.boulder.ibm.com/infocenter/tivihelp/v4r1/index.jsp?topic=/com.ibm.tpc_V33.doc/fqz0_r_valid_userids_and_passwords.html
         Dim _Symbols As New List(Of String)({"`", "~", "@", "#", "%", "^", "&", "*", "(", ")", _
                                          "-", "_", "=", "+", "[", "]", "{", "}", "\", "|", _
                                          ";", ":", "'", """", ",", ".", "<", ">", "/", "?"})
    
         'list of A-Z,a-z, 0-9 / characters we will use to build our string.
         Dim ListChars As New List(Of 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", "Z", _
                                  "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"})
    
         Dim History As New List(Of String) 'holds all the strings we generate so we do not get a double.
    
         'leaving the next 2 subs public just incase you want to add your own symbols.
         'remove certain characters from the list we use to build our strings
         Public Sub RemoveCharacters(ByVal characters As List(Of String))
              For i As Integer = 0 To characters.Count - 1
                   ListChars.Remove(characters(i).ToString)
              Next
         End Sub
    
         'add certain characters from the list we use to build our strings
         Public Sub AddCharacters(ByVal characters As List(Of String))
              ListChars.AddRange(characters.ToList)
         End Sub
    
         'adds the 30 acceptable symbols to the list of characters with which we will build our string from.
         Public Sub EnableSymbols()
              AddCharacters(_Symbols.ToList)
         End Sub
    
         'removes the 30 acceptable symbols from the list of the characters used to build our strings.
         Public Sub DisableSymbols()
              RemoveCharacters(_Symbols.ToList)
         End Sub
    
         Public Function GenerateString(ByVal length As Integer) As String
              Dim RandNumb As New Random
              Dim StrBld As New StringBuilder
    
              If length > 0 Then
                   Do Until Not History.Contains(StrBld.ToString) AndAlso StrBld.Length >= length
                        For i As Integer = 0 To length - 1
                             StrBld.Append(ListChars(RandNumb.Next(0, ListChars.Count - 1)))
                        Next
                   Loop
    
                   History.Add(StrBld.ToString)
                   Return StrBld.ToString
              Else
                   Return String.Empty
              End If
         End Function
    
     
    End Class
    CodeBank Posts: Base Converter

  10. #10
    Stack Overflow mod​erator
    Join Date
    May 2008
    Location
    British Columbia, Canada
    Posts
    2,824

    Re: Generate Random String (Letters & Numbers)

    Eeew!!

    Code:
    Public Class RandomStringMaker
         Private letters() As Char {}
         Private symbols() As Char {}
         Private m_UseSymbols As Boolean = False
         Public Property UseSymbols() As Boolean
              Get
                   Return m_UseSymbols
              End Get
              Set(ByVal value As Boolean)
                   m_UseSymbols = value
              End Set
         End Property
         Public Sub New()
              letters = New Char(90-65+122-97+1) {}
              For i As Integer = 65 To 90
                   letters(i - 65) = Chr(i)
              Next
              For i As Integer = 97 To 122
                   letters(i - 90) = Chr(i)
              Next
              symbols = New Char() {"`"c, "~"c, "@"c, "#"c, "&#37;"c, "^"c, "&"c, "*"c, "("c, ")"c, _
                                          "-"c, "_"c, "="c, "+"c, "["c, "]"c, "{"c, "}"c, "\"c, "|"c, _
                                          ";"c, ":"c, "'"c, """"c, ","c, "."c, "<"c, ">"c, "/"c, "?"c}
         End Sub
    
         Public Function GenerateString(ByVal length As Integer) As String
              Dim r As New Random()
              Dim str(length - 1) As Char
              For i As Integer = 0 To length - 1
                   If r.Next(0, 2) = 0 Then 'Use letter
                        str(i) = letters(r.Next(0, letters.Length))
                   ElseIf Me.UseSymbols Then 'Use symbol
                        str(i) = symbols(r.Next(0, symbols.Length))
                   End If
              Next
              Return New String(str)
         End Function
    End Class
    I typed this into the Quick Reply window, so sorry if it's not 100% accurate

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width