c++ - Strchr 不工作,或者我需要一个替代方法来检查给定字符串中的任何字符是否属于另一个字符串

标签 c++ string codeblocks fstream strchr

所以我正在尝试检查一个字符串,看看它是否:

  1. 有 8 个或更多字符
  2. 至少有一个大写字母
  3. 至少有一个小写字母
  4. 至少有以下字符之一 .,?!;:_!@#

这是我的代码:

#include <fstream>
#include <string.h>
using namespace std;
char a[51];
int n,i,countcheck,hardc;
int main()
{
    ifstream fin("parole.in");
    ofstream fout("parole.out");
    fin >> n;
    for (i=1;i<=n;i++)
    {
        fin >> a;
        if(strlen(a)>=8)countcheck++;
        if(strchr(a,'ABCDEFGHIJKLMNOPQRSTUVWXYZ'))countcheck++;
        if(strchr(a,'abcdefghijklmnopqrstuvwxyz'))countcheck++;
        if(strchr(a,'.,?!;:_!@#'))countcheck++;
        if (countcheck==4)hardc++;
        countcheck=0;
    }
    fout << hardc << '\n';
    fin.close();
    fout.close();
    return 0;
}

提前致谢!

最佳答案

在 C++ 中,倾向于将 std::string 用于字符数组。然后,您可以使用 std::any_of 和/或 std::string::find_first_of 等算法。这是同时使用两者的示例:

#include <string>
#include <algorithm>

bool checkString(const std::string& str)
{
    return str.length() >= 8
        && std::any_of(str.begin(), str.end(), ::isupper)
        && std::any_of(str.begin(), str.end(), ::islower)
        && str.find_first_of(".,?!;:_@#") != std::string::npos;
}

checkString 的用法:

#include <iostream>

int main()
{
    std::string tests[] {
        "Test.123",
        "Test#@#$",
        ".,?!;:_@",
        "7Chars!",
        "abcd.123",
        "ABCD.123"
    };

    for (const auto& s : tests)
        std::cout << s << (checkString(s) ? " \t-GOOD\n" : " \t-BAD\n");
}

输出:

Test.123    -GOOD
Test#@#$    -GOOD
.,?!;:_@    -BAD
7Chars!     -BAD
abcd.123    -BAD
ABCD.123    -BAD

Live Demo

关于c++ - Strchr 不工作,或者我需要一个替代方法来检查给定字符串中的任何字符是否属于另一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29282448/

相关文章:

c++ - 编译简单的 hello world 程序时错误泛滥

c++ - C++03 中的 <functional> 函数对象有什么用处?

string - 将字符串变量转换为整数的最有效 VBA 代码

C++ - 对最近创建的类的 undefined reference !

c - 代码块中的 "No such file or directory"错误

c++ - 无法在 Windows XP 上编译 rsa.h

C++:如何将模板数组声明为函数参数

c++ - C++ 中 protobuf 消息的长度前缀

从 C 中的文本文件复制所需的字符串

c++ - 根据字符串表示设置枚举值