c# - 不使用 RegEx 和/或列表/规则的密码检查
问题描述
我搜索了论坛和整个谷歌,但还没有找到我的问题的答案。我想用一个带有 if/if else 语句的 for 循环创建一个简单的程序。如果不使用 RegEx 或列表/规则,这可能吗?
我希望它符合这些要求:
长度 8. 至少一位数。至少一个大写字母。至少一个小写字母。
这是我迄今为止提出的,我不明白为什么它不起作用?我有 if 语句而没有 else if 的原因是因为如果不满足条件,我希望打印所有错误消息。为愚蠢的问题道歉,我是 C# 的新手。
static void Main(string[] args)
{
var password = Console.ReadLine();
for (var i = 0; i < password.Length; ++i)
{
bool hasDigit = char.IsDigit(password[i]);
bool hasUpperCase = char.IsUpper(password[i]);
bool hasLowerCase = char.IsLower(password[i]);
if(password.Length < 8)
{
Console.WriteLine("Password length should be 8 symbols or more.");
}
if(!hasUpperCase)
{
Console.WriteLine("Password should contain at least one uppercase letter.");
}
if(!hasLowerCase)
{
Console.WriteLine("Password should contain at least one lowercase letter.");
}
if(!hasDigit)
{
Console.WriteLine("Password should contain at least one digit.");
}
password = Console.ReadLine();
}
Console.WriteLine("Your password is properly set!");
Console.ReadLine();
}
解决方案
您的循环每回合检查一个字符。这意味着只有一个布尔值会返回 true。您应该改为在循环之外进行检查,例如:
bool hasDigit = false;
bool hasUpperCase = false;
bool hasLowerCase = false;
for (var i = 0; i < password.Length; ++i)
{
hasDigit = hasDigit || char.IsDigit(password[i]);
hasUpperCase = hasUpperCase || char.IsUpper(password[i]);
hasLowerCase = hasLowerCase || char.IsLower(password[i]);
}
if(password.Length < 8)
{
Console.WriteLine("Password length should be 8 symbols or more.");
}
if(!hasUpperCase)
{
Console.WriteLine("Password should contain at least one uppercase letter.");
}
if(!hasLowerCase)
{
Console.WriteLine("Password should contain at least one lowercase letter.");
}
if(!hasDigit)
{
Console.WriteLine("Password should contain at least one digit.");
}
另一种选择是使用 linq,因此您不需要 for 循环,如下所示:
if(password.Length < 8)
{
Console.WriteLine("Password length should be 8 symbols or more.");
}
if(!password.Any(x=>char.IsUpper(x)))
{
Console.WriteLine("Password should contain at least one uppercase letter.");
}
if(!password.Any(x=>char.IsLower(x)))
{
Console.WriteLine("Password should contain at least one lowercase letter.");
}
if(!password.Any(x=>char.IsDigit(x)))
{
Console.WriteLine("Password should contain at least one digit.");
}
推荐阅读
- node.js - 如何将容器内生成的 package-lock.json 文件传递给我的源代码?
- html - Firefox和Chrome中CSS行高中的箭头不同
- c++ - 求方程的根
- javascript - 如何在按下“Enter”键时调用函数
- c - 在文件上写入和读取链表堆栈不相同
- angular - 关于验证码授权实现的一个问题
- vimeo - Vimeo 视频 ajax 上传
- python - HiveContext 不保持 SparkContext conf
- azure-devops - Azure DevOps:使用 REST API 在组织之间移动包
- apache-kafka - Kafka Nodes 和 zookeeper 将如何相互通信?