生成随机字符串的问题
工作中经常需要生成不重复的随机字符串。
使用random来生成的话。短时间内生成的重复太多如这篇文章的 http://www.cnblogs.com/smhy8187/articles/888729.html
现发现关于重复太多也是有办法解决的 就是Random类定义成 静态类.
和这篇文章的http://www.cnblogs.com/insus/articles/1396908.html 我都试验了。效果都不是很好。
考虑使用 Guid来截取效果可能不错试验了一下效果还可以。如果想使用全部字母的话。可以考虑和前面提到的两个连接的文章结合起来创建到字母表的映射修改一个算法出来。
class Program
{
static void Main(string[] args)
{
List<string> list = new List<string>();
int count = 8000, lenght = 6;
int had = 0;
while (list.Count < count)
{
for (int i = 0; i < count -had; i++)
{
string s = Guid.NewGuid().ToString().Replace("-","").Substring(0,lenght);//obj.RandomNumber(true, true, 6);
list.Add(s);
}
for (int i = 0; i < list.Count - 1; i++)
{
for (int j = i + 1; j < list.Count; j++)
{
if (list[i].Equals(list[j]))
{
list.RemoveAt(j);
j--;
}
}
}
had = list.Count;
Console.WriteLine(had);
}
Console.Write(list.Count);
Console.ReadLine();
}
}
{
static void Main(string[] args)
{
List<string> list = new List<string>();
int count = 8000, lenght = 6;
int had = 0;
while (list.Count < count)
{
for (int i = 0; i < count -had; i++)
{
string s = Guid.NewGuid().ToString().Replace("-","").Substring(0,lenght);//obj.RandomNumber(true, true, 6);
list.Add(s);
}
for (int i = 0; i < list.Count - 1; i++)
{
for (int j = i + 1; j < list.Count; j++)
{
if (list[i].Equals(list[j]))
{
list.RemoveAt(j);
j--;
}
}
}
had = list.Count;
Console.WriteLine(had);
}
Console.Write(list.Count);
Console.ReadLine();
}
}