我生成一个包含62个选项的字符串^ 6个字母= 56,800,235,584
但是在运行代码时,它会重复相同的字符串,少于每200,200次
这里有什么问题?
顺便说一句: 此代码基于答案here
class Program
{
static void Main(string[] args)
{
var d = new Dictionary<string, bool>();
for (int i = 0; ; i++)
{
var s = GenerateString(6);
try
{
d.Add(s, false);
}
catch (Exception ex)
{
Console.WriteLine(String.Format("{0} - {1} - {2}", i, s, ex.Message));
i = 0;
}
}
Console.ReadKey();
}
static Random _rnd = new Random();
public static string GenerateString(int len)
{
const string bigLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const string smallLetters = "abcdefghijklmnopqrstuvwxyz";
const string numbers = "1234567890";
var validChars = bigLetters + smallLetters + numbers;
var result = new StringBuilder();
for (int i = 0; i < len; i++)
{
result.Append(validChars[_rnd.Next(validChars.Length)]);
}
return result.ToString();
}
}
答案 0 :(得分:6)
答案 1 :(得分:1)
为避免重复,您可以在将字符串添加到列表之前检查是否存在:
在GenerateString()
if(d.Contains(result.ToString()) // check whether the current generated string is in the list
{
GenerateString(len); // if it is already existed generate another one
}
else
{
return result.ToString(); // if not then return the string
}