如何生成一个随机字符串,然后指定你想要的长度,或者更好的规范生成唯一的字符串你想 [英] how to generate a random string, and specify the length you want, or better generate unique string on specification you want
问题描述
有是产生随机数的图书馆,为什么in't那里产生随机字符串?
在换句话说如何生成一个随机字符串图书馆,并指定你想要的长度,或者更好的生成规范的唯一字符串你想即
指定长度,我的应用程序中的唯一的字符串是对我来说足够。
我知道我可以创建一个GUID(全局唯一标识符),但这些都是很长,时间越长,需要的人。
INT长度= 8;
字符串s = RandomString.NextRandomString(长)
uniquestringCollection =新UniquestringsCollection(长)
字符串s2 = uniquestringCollection.GetNext();
我不记得在那里我得到了这一点,所以如果你知道是谁最初创作这一点,请大家帮我给归属。
私有静态无效的主要()
{
常量字符串AllowedChars =
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#@ $ ^ *();
随机RNG =新的随机();
的foreach
{
Console.WriteLine(randomString)(以RandomStrings(AllowedChars,1,16,25,RNG)变种randomString);
}
到Console.ReadLine();
}
私有静态的IEnumerable<串GT; RandomStrings(
串allowedChars,
INT的minLength,
INT最大长度,
诠释计数,
随机RNG)
{
的char []字符=新的char [最大长度]
INT SetLength函数= allowedChars.Length;
,而(count--大于0)
{
INT长度= rng.Next(的minLength,最大长度+ 1);
的for(int i = 0; I<长度; ++ I)
{
字符由[i] = allowedChars [rng.Next(SetLength函数)];
}
收益返回新的字符串(字符,0,长度);
}
}
There is a library to generate Random numbers, so why in't there a library for generation random strings ?
In other words how to generate a random string, and specify the length you want, or better generate unique string on specification you want i.e specify the length, a unique string within my application is enough for me.
I know I can create a Guid (globally unique identifier) but those are quite long, longer they need to be.
int length = 8;
string s = RandomString.NextRandomString(length)
uniquestringCollection = new UniquestringsCollection(length)
string s2 = uniquestringCollection.GetNext();
I can't recall where I got this, so if you know who originally authored this, please help me give attribution.
private static void Main()
{
const string AllowedChars =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#@$^*()";
Random rng = new Random();
foreach (var randomString in RandomStrings(AllowedChars, 1, 16, 25, rng))
{
Console.WriteLine(randomString);
}
Console.ReadLine();
}
private static IEnumerable<string> RandomStrings(
string allowedChars,
int minLength,
int maxLength,
int count,
Random rng)
{
char[] chars = new char[maxLength];
int setLength = allowedChars.Length;
while (count-- > 0)
{
int length = rng.Next(minLength, maxLength + 1);
for (int i = 0; i < length; ++i)
{
chars[i] = allowedChars[rng.Next(setLength)];
}
yield return new string(chars, 0, length);
}
}
这篇关于如何生成一个随机字符串,然后指定你想要的长度,或者更好的规范生成唯一的字符串你想的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!