How to make random string of numbers and letters w

2019-03-14 15:46发布

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!

标签: c# string random
3条回答
女痞
2楼-- · 2019-03-14 16:16

replace

ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));

by

string chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
ch=chars[random.Next(chars.Length)];

Note that your code doesn't create unpredictable random strings. In particular there are only 2 billion possible results, and if your computer gets restarted often, some of them are much more likely than others.

If you want unpredictable random strings, you should use RNGCryptoServiceProvider. You can fine an example at https://stackoverflow.com/a/1344255/445517 , you just need to add the hyphens.

查看更多
戒情不戒烟
3楼-- · 2019-03-14 16:31

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());
}
查看更多
Ridiculous、
4楼-- · 2019-03-14 16:35

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);
}
查看更多
登录 后发表回答