Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random strings in vb.net

Tags:

random

vb.net

I need to generate random strings in vb.net, which must consist of (randomly chosen) letters A-Z (must be capitalized) and with random numbers interspersed. It needs to be able to generate them with a set length as well.

Thanks for the help, this is driving me crazy!

like image 293
Cyclone Avatar asked Oct 09 '09 23:10

Cyclone


2 Answers

If you can convert this to VB.NET (which is trivial) I'd say you're good to go (if you can't, use this or any other tool for what's worth):

/// <summary>
/// The Typing monkey generates random strings - can't be static 'cause it's a monkey.
/// </summary>
/// <remarks>
/// If you try hard enough it will eventually type some Shakespeare.
/// </remarks>
class TypingMonkey
{
   private const string legalCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

   static Random random = new Random();

   /// <summary>
   /// The Typing Monkey Generates a random string with the given length.
   /// </summary>
   /// <param name="size">Size of the string</param>
   /// <returns>Random string</returns>
   public string TypeAway(int size)
   {
       StringBuilder builder = new StringBuilder();
       char ch;

       for (int i = 0; i < size; i++)
       {
           ch = legalCharacters[random.Next(0, legalCharacters.Length)];
           builder.Append(ch);
       }

       return builder.ToString();
    }
}

Then all you've got to do is:

TypingMonkey myMonkey = new TypingMonkey();
string randomStr = myMonkey.TypeAway(size);
like image 123
JohnIdol Avatar answered Oct 21 '22 04:10

JohnIdol


Why don't you randomize a number 1 to 26 and get the relative letter.

Something like that:

Dim output As String = ""
Dim random As New Random()
For i As Integer = 0 To 9
   output += ChrW(64 + random.[Next](1, 26))
Next

Edit: ChrW added.

Edit2: To have numbers as well

    Dim output As String = ""
    Dim random As New Random()

    Dim val As Integer
    For i As Integer = 0 To 9
        val = random.[Next](1, 36)
        output += ChrW(IIf(val <= 26, 64 + val, (val - 27) + 48))
    Next
like image 30
JCasso Avatar answered Oct 21 '22 06:10

JCasso