tags:

views:

1182

answers:

5

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!

A: 

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
JCasso
You forgot about the numbers. :)
MusiGenesis
Who? me? :) Thanks. Added.
JCasso
+4  A: 

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);
JohnIdol
I lol'd @ the monkey thing ;)
Cyclone
You included lower-case letters and a `.`. *And* you have the Snake Plissken thing going. :)
MusiGenesis
Lower-case etc all gone. Snake Plissken will never go :)
JohnIdol
It may be a bit more of a hassle to use, but it works and it amuses me
Cyclone
Since you know the size of the data, you might as well initialize the StringBuilder with this value. This will avoid unnecessary memory allocations. Great answer though +1.
Phaedrus
@Phaedrus good comment - thanks!
JohnIdol
@Cyclone the amusement makes it worthwhile ;) - look here if you're curious as to where I currently use this piece of code --> http://github.com/JohnIdol/typingmonkey/blob/master/TypingMonkey/TypingMonkey.cs
JohnIdol
@John: Very amusing ;)
Cyclone
+1 for the monkey
Meta-Knight
(and for the good answer, I wish I could give +2 :P)
Meta-Knight
@Meta-Knight thanks :) - looks like someone else didn't like the monkey though, as I just got down-voted ;-/
JohnIdol
A: 

C#

public string RandomString(int length)
{
    Random random = new Random();
    char[] charOutput = new char[length];
    for (int i = 0; i < length; i++)
    {
        int selector = random.Next(65, 101);
        if (selector > 90)
        {
            selector -= 43;
        }
        charOutput[i] = Convert.ToChar(selector);
    }
    return new string(charOutput);
}

VB.Net

Public Function RandomString(ByVal length As Integer) As String 
    Dim random As New Random() 
    Dim charOutput As Char() = New Char(length - 1) {} 
    For i As Integer = 0 To length - 1 
        Dim selector As Integer = random.[Next](65, 101) 
        If selector > 90 Then 
            selector -= 43 
        End If 
        charOutput(i) = Convert.ToChar(selector) 
    Next 
    Return New String(charOutput) 
End Function
MusiGenesis
http://www.developerfusion.com/tools/convert/csharp-to-vb/ Use that next time lol, that way I don't have to ;)
Cyclone
@Cyclone: *very* cool link. I'm a VB programmer again!!!
MusiGenesis
Hey! I linked that as well - and I got the monkey ;)
JohnIdol
You're welcome lol! It even converts back to c# so you can use our vb source in your c# stuff ;). John, I don't see a link anywhere lol? But your monkey is highly amusing, I can't deny it!
Cyclone
@Cyclone: just switch to C#, already. Come over to the dark side. :)
MusiGenesis
quote: [if you can't, use -->this<-- there's the link, not that it matters ;-)
JohnIdol
I *was* making a game in c# cause thats what I was told to make it in, but then I realized that if the server can execute a c# .dll then it can certainly do a vb.net one lol
Cyclone
@JohnIdol: huh?
MusiGenesis
@john: Didn't see it, sorry :S. Now I do lol, I love that tool xD
Cyclone
@MusiGenesis: Your code generates a single random string, once, then never regenerates till you restart the app? Whats up with that lol?
Cyclone
@Cyclone: in the C# world, creating a new Random object with the empty constructor seeds it with the system time, so the C# version of my function will return a different string every time you call it (unless you call it twice within a few milliseconds and thus seed with the same system time). I'm guessing in VB.Net Random uses the same seed every time until you restart the app. You *really* need to switch to C#, dude. :)
MusiGenesis
>(unless you call it twice within a few milliseconds and thus seed with the same system time) Erm, its generating like 1000 pieces of text without any intended pause lol.
Cyclone
+1  A: 

How about:

Private Function GenerateString(len as integer) as String
        Dim stringToReturn as String=""
        While stringToReturn.Length<len
           stringToReturn&= Guid.NewGuid.ToString().replace("-","")
        End While
        Return left(Guid.NewGuid.ToString(),len)
End Sub
NickAtuShip
Clever. Add in the Replace code and deal with strings longer than 1 Guid, and I'll upvote you.
MusiGenesis
A: 

Here's a utility class I've got to generate random passwords. It's similar to JohnIdol's Typing Monkey, but has a little more flexibility in case you want generated strings to contain uppercase, lowercase, numeric or special characters.

public static class RandomStringGenerator
{
 private static bool m_UseSpecialChars = false;

 #region Private Variables

 private const int m_MinimumLength = 8;
 private const string m_LowercaseChars = "abcdefghijklmnopqrstuvqxyz";
 private const string m_UppercaseChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 private const string m_NumericChars = "123456890";
 private const string m_SpecialChars = "~?/@#!£$%^&*+-_.=|";

 #endregion

 #region Public Methods

 /// <summary>
 /// Generates string of the minimum length
 /// </summary>
 public static string Generate()
 {
  return Generate(m_MinimumLength);
 }

 /// <summary>
 /// Generates a string of the specified length
 /// </summary>
 /// <param name="length">The number of characters to generate</param>
 public static string Generate(int length)
 {
  return Generate(length, Environment.TickCount);
 }

 #endregion

 #region Private Methods

 /// <summary>
 /// Generates a string of the specified length using the specified seed
 /// </summary>
 private static string Generate(int length, int seed)
 {
  // Generated strings must contain at least 3 of the following character groups: uppercase letters, lowercase letters
  // numerals, and special characters (!, #, $, £, etc)

  // The generated string must be at least 4 characters  so that we can add a single character from each group.
  if (length < 4) throw new ArgumentException("String length must be at least 4 characters");

  StringBuilder SB = new StringBuilder();

  Random rand = new Random(seed);

  // Ensure that we add all of the required groups first
  SB.Append(GetRandomCharacter(m_LowercaseChars, rand));
  SB.Append(GetRandomCharacter(m_UppercaseChars, rand));
  SB.Append(GetRandomCharacter(m_NumericChars, rand));

  if (m_UseSpecialChars)
   SB.Append(GetRandomCharacter(m_SpecialChars, rand));

  // Now add random characters up to the end of the string
  while (SB.Length < length)
  {
   SB.Append(GetRandomCharacter(GetRandomString(rand), rand));
  }

  return SB.ToString();
 }

 private static string GetRandomString(Random rand)
 {
  int a = rand.Next(3);
  switch (a)
  {
   case 1:
    return m_UppercaseChars;
   case 2:
    return m_NumericChars;
   case 3:
    return (m_UseSpecialChars) ? m_SpecialChars : m_LowercaseChars;
   default:
    return m_LowercaseChars;
  }
 }

 private static char GetRandomCharacter(string s, Random rand)
 {
  int x = rand.Next(s.Length);

  string a = s.Substring(x, 1);
  char b = Convert.ToChar(a);

  return (b);
 }

 #endregion
}

To use it:

string a = RandomStringGenerator.Generate();   // Generate 8 character random string
string b = RandomStringGenerator.Generate(10); // Generate 10 character random string

This code is in C# but should be fairly easy to convert to VB.NET using a code converter.

Mun