自动生成随机字母数字字符?

时间:2011-09-22 10:54:15

标签: c# string random

  

可能重复:
  How to get random string with spaces and mixed case?

如何自动生成随机字母商业字符

Valid characters: Uppercase (A-Z), Lowercase (a-z), and digits (0-9)
Size: 6

2 个答案:

答案 0 :(得分:3)

试试这个:

string def = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random rnd = new Random();
StringBuilder ret = new StringBuilder();
for (int i = 0; i < 6; i++)
    ret.Append(def.Substring(rnd.Next(def.Length), 1));
return ret.ToString();

答案 1 :(得分:1)

这样的事情:

        var possibleChars = new List<char>();
        for(var c='a';c<='z';c++)
        {
            possibleChars.Add(c);
        }
        for (var c = 'A'; c <= 'Z'; c++)
        {
            possibleChars.Add(c);
        }
        for (var c = '0'; c <= '9'; c++)
        {
            possibleChars.Add(c);
        }
        var r = new Random();
        var randomChar = possibleChars[r.Next(possibleChars.Count)];