gpt4 book ai didi

c++ - 使用 “any_of”时如何检查字符串是否没有特定符号?

转载 作者:行者123 更新时间:2023-12-02 10:04:38 26 4
gpt4 key购买 nike

我正在尝试检查一个字符串以查看它是否满足所有要求,而这些要求之一是没有'*''%'。使用std::any_of检查整个字符串,并使其与isupperislower一起使用,但无法为这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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com