我正在尝试检查一个字符串以查看它是否满足所有要求,而这些要求之一是没有'*'
或'%'
。使用std::any_of
检查整个字符串,并使其与isupper
和islower
一起使用,但无法为这2个字符弄清楚。
到目前为止,我所获得的样本中,第三个if语句就我所知。
if(std::any_of(nPass.cbegin(), nPass.cend(), ::isupper))
{
if(std::any_of(nPass.cbegin(), nPass.cend(), ::islower) )
{
if(std::any_of(nPass.cbegin(), nPass.cend(), ::!='*'))
{
return true; // returns true if all criteria is met
}
}
}
最佳答案
不需要对第三项检查使用算法std::any_of。您可以使用find_first_of
类的std::string
方法。
这是一个演示程序。
#include <iostream>
#include <iomanip>
#include <string>
#include <iterator>
#include <algorithm>
#include <cctype>
bool check( const std::string &s )
{
return std::any_of( std::begin( s ), std::end( s ), ::isupper ) &&
std::any_of( std::begin( s ), std::end( s ), ::islower ) &&
s.find_first_of( "*% " ) == std::string::npos;
}
int main()
{
std::cout << std::boolalpha << check( "A" ) << '\n';
std::cout << std::boolalpha << check( "a" ) << '\n';
std::cout << std::boolalpha << check( "Aa%" ) << '\n';
std::cout << std::boolalpha << check( "Aa*%" ) << '\n';
std::cout << std::boolalpha << check( "Aa" ) << '\n';
return 0;
}
它的输出是
false
false
false
false
true
我想字符串必须同时包含大写和小写字母。如果仅检查字母字符,则可以使用
::isalpha
。
关于c++ - 使用 “any_of”时如何检查字符串是否没有特定符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60908714/