我需要编写一个密码生成器来生成一个密码,该密码具有最小值。2 个小写字母,最少 2 个大写字母,最少 1 位数和分钟。1 个特殊字符。它还必须是用户给定的长度。如何使用此代码为密码提供最小长度。例如:10?
这就是我一直在遭受的痛苦,但我试图限制长度但没有任何成功,所以我只是删除了这些代码:
class Program
{
private const string Capital = "ABCDEFGHIJKLMNOUP";
private const string Lower = "abcdefghijklmnoup";
private const string Digit = "1234567890";
private const string Spec = "@&#><-[]Łł$ß";
private const string AllChars = Capital + Lower + Digit + Spec;
private static Random r = new Random();
static void Main(string[] args)
{
StringBuilder password = new StringBuilder();
for (int i = 1; i <= 2; i++)
{
char capitalLetter = GenerateChar(Capital);
InsertAtRandomPos(password, capitalLetter);
}
for (int i = 1; i <= 2; i++)
{
char lowerLetter = GenerateChar(Lower);
InsertAtRandomPos(password, lowerLetter);
}
for (int i = 1; i <= 3; i++)
{
char digit = GenerateChar(Digit);
InsertAtRandomPos(password, digit);
}
for (int i = 1; i <= 1; i++)
{
char specialLetter = GenerateChar(Spec);
InsertAtRandomPos(password, specialLetter);
}
Console.WriteLine("A jelszava: {0}",password);
Console.ReadKey();
}
private static void InsertAtRandomPos(StringBuilder password, char character)
{
int randomPosition = r.Next(password.Length + 1);
password.Insert(randomPosition, character);
}
private static char GenerateChar(string availableChars)
{
int randomIndex = r.Next(availableChars.Length);
char randomChar = availableChars[randomIndex];
return randomChar;
}
}
}