首页 > 解决方案 > 如何检查字符串是否包含所有这些:数字、字母和特殊字符?

问题描述

我正在尝试构建一个简单的密码验证器:

程序打印

如您所见,我知道如何检查字符串是否具有三种字符中的一种。如何检查字符串是否包含两个或全部三个?

#include <iostream>
#include <ctype.h>
#include <cstring>

int main()
{
    std::cout << "Enter your new password: ";
    std:: string password{};
    std::cin >> password;

    bool veryweak;
    bool weak;
    bool strong;
    bool verystrong;

    if (password.length() < 8)
    {
        for (int i = 0; i < password.length(); i++)
            {
                if (isdigit(password[i]))
                {
                    veryweak = true;
                }

                else if (isalpha(password[i]))
                {
                    weak = true;
                }
            }
    }

    else if (password.length() >= 8)
    {
        for (int i = 0; i < password.length(); i++)
        {
            //if (password has digits and alphabets)
                //strong = true;

            //if (password has digits and alphabet and special characters)
                //verystrong = true;
        }
    }

    else
    {
        std::cout << "Password is invalid.";
    }
    //---------------------------------------------------------------------------------------------------------------------
    if (veryweak)
    {
        std::cout << "Your password is very weak.";
    }

    else if (weak)
    {
        std::cout << "Your password is weak.";
    }

    else if(strong)
    {
        std::cout << "Your password is strong.";
    }

    else if (verystrong)
    {
        std::cout << "Your password is very strong.";
    }

    return 0;
}

标签: c++

解决方案


你为什么不使用一些计数器,比如weak_counter 之类的。对于每个满足的属性,计数器都加一。最后,您检查满足了多少属性并在此之后评估密码强度。

此外,我建议您为每个属性编写一个自己的函数,例如:

bool containsNumbers(string pw);
bool containsLetters(string pw);

等等。在这种情况下,通过新属性等更容易阅读、更改和扩展代码。

我希望我能帮助你。

问候 :)


推荐阅读