如何在C#中生成格式化的字母数字字符串

时间:2014-11-10 09:27:33

标签: c#

我想生成带有5个字母数字字符的随机字符串,但是应该生成两个字符而其他字符应该是数字的

 RL589

为此,我做了

        var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        var stringChars = new char[5];
        var random = new Random();

        for (int i = 0; i < stringChars.Length; i++)
        {
            stringChars[i] = chars[random.Next(chars.Length)];
        }

        var finalString = new String(stringChars);

但是我很困惑如何安排前两个字母是字符而另一个应该是数字。请帮助我。

5 个答案:

答案 0 :(得分:4)

生成两个字符串。一个字符和一个数字。然后,将它们连接起来。

答案 1 :(得分:2)

使用两个循环,例如:

var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var numbers = "0123456789";
var stringChars = new char[5];
var random = new Random();

for (int i = 0; i < 2; i++)
{
  stringChars[i] = chars[random.Next(chars.Length)];
}
for (int i = 2; i < stringChars.Length; i++)
{
  stringChars[i] = numbers[random.Next(numbers.Length)];
}

var finalString = new String(stringChars);

答案 2 :(得分:0)

var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var numbers = "0123456789";

var stringChars = new char[5];

var random = new Random();

for (int i = 0; i < stringChars.Length; i++)
{
    if (i < 2)
    {
        stringChars[i] = letters[random.Next(letters.Length)];
    }
    else
    {
        stringChars[i] = numbers[random.Next(numbers.Length)];
    }
}

var finalString = new String(stringChars);

答案 3 :(得分:0)

您不需要任何字符串。只需使用charint之间的隐式转换:

var stringChars = new char[5];
var random = new Random();

for (int i = 0; i < 2; i++)
{
    stringChars[i] = (char)random.Next('A', 'Z');
}
for (int i = 2; i < 5; i++)
{
    stringChars[i] = (char)random.Next('0', '9');
}

var finalString = new String(stringChars);

答案 4 :(得分:0)

为什么不使用Random对象创建随机数?

var stringChars = new StringBuilder();
var random = new Random();

for (int i = 0; i < 2; i++)
{
    stringChars.Append((char)random.Next('A', 'Z'));
}

var finalString = string.Format("{0}{1}{2}{3}", stringChars.ToString()
    , random.Next(1, 9)
    , random.Next(1, 9)
    , random.Next(1, 9));

或只是

var finalString = string.Format("{0}{1}", stringChars.ToString()
        , random.Next(100, 999));

为什么StringBuilder,字符串连接总是创建一个新实例,所以你应该避免这种情况。