gpt4 book ai didi

c# - 如何生成一个随机字符串,并指定你想要的长度,或者更好地生成你想要的规范的唯一字符串

转载 作者:IT王子 更新时间:2023-10-29 04:03:25 28 4
gpt4 key购买 nike

有生成随机数的库,为什么没有生成随机字符串的库呢?

换句话说,如何生成一个随机字符串,并指定所需的长度,或者更好的是,根据您想要的规范生成唯一的字符串,即指定长度,我的应用程序中的唯一字符串对我来说就足够了。

我知道我可以创建一个 Guid(全局唯一标识符),但是它们很长,需要更长的时间。

int length = 8;
string s = RandomString.NextRandomString(length)
uniquestringCollection = new UniquestringsCollection(length)
string s2 = uniquestringCollection.GetNext();

最佳答案

我不记得我是从哪里得到这个的,所以如果你知道这篇文章的原作者,请帮我注明出处。

private static void Main()
{
const string AllowedChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#@$^*()";
Random rng = new Random();

foreach (string randomString in rng.NextStrings(AllowedChars, (15, 64), 25))
{
Console.WriteLine(randomString);
}

Console.ReadLine();
}

private static IEnumerable<string> NextStrings(
this Random rnd,
string allowedChars,
(int Min, int Max)length,
int count)
{
ISet<string> usedRandomStrings = new HashSet<string>();
(int min, int max) = length;
char[] chars = new char[max];
int setLength = allowedChars.Length;

while (count-- > 0)
{
int stringLength = rnd.Next(min, max + 1);

for (int i = 0; i < stringLength; ++i)
{
chars[i] = allowedChars[rnd.Next(setLength)];
}

string randomString = new string(chars, 0, stringLength);

if (usedRandomStrings.Add(randomString))
{
yield return randomString;
}
else
{
count++;
}
}
}

关于c# - 如何生成一个随机字符串,并指定你想要的长度,或者更好地生成你想要的规范的唯一字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4616685/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com