Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make random string of numbers and letters with a length of 5? [duplicate]

Tags:

Possible Duplicate:
Is this a good way to generate a string of random characters?
How can I generate random 8 character, alphanumeric strings in C#?

This is the code that I have so far.

    private void button1_Click(object sender, EventArgs e)     {         string rand1 = RandomString(5);         string rand2 = RandomString(5);         string rand3 = RandomString(5);         string rand4 = RandomString(5);         string rand5 = RandomString(5);         textBox1.Text = rand1 + "-" + rand2 + "-" + rand3 + "-" + rand4 + "-" + rand5;      }     private static Random random = new Random((int)DateTime.Now.Ticks);     private string RandomString(int Size)     {         StringBuilder builder = new StringBuilder();         char ch;         for (int i = 0; i < Size; i++)         {             ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));             builder.Append(ch);         }         return builder.ToString();     } 

BUT it just creates a random string of 5 chars. I want it to create a string of 5 chars and integers. How would I do this? Thanks in advance!

like image 597
Ian Lundberg Avatar asked Apr 03 '12 14:04

Ian Lundberg


People also ask

How do you generate a random string of a fixed length in go?

Previous solutions get a random number to designate a random letter by calling rand. Intn() which delegates to Rand. Intn() which delegates to Rand. Int31n() .


2 Answers

Use an input array to draw your values from:

private static string RandomString(int length) {     const string pool = "abcdefghijklmnopqrstuvwxyz0123456789";     var builder = new StringBuilder();      for (var i = 0; i < length; i++)     {         var c = pool[random.Next(0, pool.Length)];         builder.Append(c);     }      return builder.ToString(); } 

Or the (inevitable) Linq solution:

private static string RandomString(int length) {     const string pool = "abcdefghijklmnopqrstuvwxyz0123456789";     var chars = Enumerable.Range(0, length)         .Select(x => pool[random.Next(0, pool.Length)]);     return new string(chars.ToArray()); } 
like image 53
BrokenGlass Avatar answered Oct 15 '22 15:10

BrokenGlass


Copying from jon skeet's answer... https://stackoverflow.com/a/976674/67824

Random rand = new Random();  public const string Alphabet =  "abcdefghijklmnopqrstuvwyxzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  public string GenerateString(int size) {     char[] chars = new char[size];     for (int i=0; i < size; i++)     {         chars[i] = Alphabet[rand.Next(Alphabet.Length)];     }     return new string(chars); } 
like image 25
Ohad Schneider Avatar answered Oct 15 '22 14:10

Ohad Schneider