c++ - 如何检查字符串是否包含所有这些:数字、字母和特殊字符?
问题描述
我正在尝试构建一个简单的密码验证器:
程序打印
如果密码少于 8 个字符和所有数字,则为“非常弱”。
如果密码少于 8 个字符且全部为字母,则为“弱”。
如果密码包含 8 个或更多字符并且包含数字和字母,则为“强”。
如果密码包含 8 个或更多字符并包含数字、字母和特殊字符,则为“非常强”。
如您所见,我知道如何检查字符串是否具有三种字符中的一种。如何检查字符串是否包含两个或全部三个?
#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;
}
解决方案
你为什么不使用一些计数器,比如weak_counter 之类的。对于每个满足的属性,计数器都加一。最后,您检查满足了多少属性并在此之后评估密码强度。
此外,我建议您为每个属性编写一个自己的函数,例如:
bool containsNumbers(string pw);
bool containsLetters(string pw);
等等。在这种情况下,通过新属性等更容易阅读、更改和扩展代码。
我希望我能帮助你。
问候 :)
推荐阅读
- c - C中的一级宏扩展
- cassandra - Cassandra 3.x 到 4.x 驱动程序的差异
- javascript - 为什么当我将某些东西推入 JSON 数组时什么都没有发生?
- python - 同时迭代多个数据帧行
- tensorflow - 如何在 tensorflow tf.data.Dataset 中使用 cv2 图像增强功能?
- java - 我可以在哪里存储程序数据?(操作系统,Java)
- rest - 无法通过空手道框架上传 zip 文件
- django - sqlite3更新与django冲突(Windows10)需要SQLite 3.8.3或更高版本(找到3.7.17))
- azure - Azure DevOps - 找不到 Azure 工件设置 - 无法删除继承
- python - 使用轮廓和轮廓绘制二维数组 grib 数据 - 为什么使用轮廓会杀死脚本?