关于C#:如何制作长度为5的随机数字和字母串?

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

本问题已经有最佳答案,请猛点这里访问。

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#?

这就是迄今为止我掌握的代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    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();
    }

但它只是创建一个5个字符的随机字符串。我希望它创建一个由5个字符和整数组成的字符串。我该怎么做?事先谢谢!


使用输入数组从以下位置绘制值:

1
2
3
4
5
6
7
8
9
10
11
12
13
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();
}

或(不可避免的)LINQ解决方案:

1
2
3
4
5
6
7
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());
}


从乔恩·斯基特的回答中复制…https://stackoverflow.com/a/976674/67824

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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);
}


代替

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

通过

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

注意,代码不会创建不可预测的随机字符串。特别是,只有20亿个可能的结果,如果你的电脑经常重启,其中一些比其他的更有可能。

如果需要不可预测的随机字符串,则应使用RngCryptoServiceProvider。您可以在https://stackoverflow.com/a/1344255/445517上创建一个示例,只需添加连字符即可。