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

标签 c++ string algorithm

我正在尝试检查一个字符串以查看它是否满足所有要求,而这些要求之一是没有'*''%'。使用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/

相关文章:

c++ - 是否允许从 CppCon 示例中进行这些编译器优化?

java - 将字符串参数转换为 StringBuffer

c++ - boost::algorithm::join 的一个很好的例子

c++ - 计算 3D 平面圆的最小半径

algorithm - 计算机象棋树搜索的最新技术水平是什么?

c++ - ld : cannot find -lstdc++

c# - MFC 对话框中使用的托管 C# 用户控件未处理的异常

c++ - 使用 boost::regex 匹配两个完整的单词

java - 找到具有特定权重的特定节点的循环路径

c++ - friend 功能不访问另一个 friend 类的私有(private)成员