首页 > 解决方案 > 不使用 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();
}

标签: c#for-loopif-statementboolean

解决方案


您的循环每回合检查一个字符。这意味着只有一个布尔值会返回 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.");
}

推荐阅读