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!
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() .
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()); }
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With