gpt4 book ai didi

c# - 如何制作以 A1A 1A1 格式返回随机字符串的方法?

转载 作者:行者123 更新时间:2023-11-30 18:56:07 26 4
gpt4 key购买 nike

我需要一种方法来返回以下格式的随机字符串:

字母编号字母编号字母编号

最佳答案

假设您不需要它是线程安全的:

private static readonly Random rng = new Random();

private static RandomChar(string domain)
{
int selection = rng.Next(domain.Length);
return domain[selection];
}

private static char RandomDigit()
{
return RandomChar("0123456789");
}

private static char RandomLetter()
{
return RandomChar("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
}

public static char RandomStringInSpecialFormat()
{
char[] text = new char[6];
char[0] = RandomLetter();
char[1] = RandomDigit();
char[2] = RandomLetter();
char[3] = RandomDigit();
char[4] = RandomLetter();
char[5] = RandomDigit();
return new string(text);
}

(您可以在 RandomStringInSpecialFormat 中使用 3 次迭代循环,但它没有太大好处。)

如果您需要它是线程安全的,您将需要一些方法来确保您不会同时从多个线程访问 Random。最简单的方法(在我看来)是使用 StaticRandom 中的 MiscUtil

关于c# - 如何制作以 A1A 1A1 格式返回随机字符串的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/308954/

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