C++ 检查字符串是否包含至少 1 个数字和 1 个字母

标签 c++

我试图在返回 true 之前检查字符串输入是否包含至少一个数字和一个字母。

我的方法是首先循环遍历单词。 如果单词不包含 isalphaisdigit,则返回 false。

检查之后,我创建了两个计数(一个用于数字,一个用于字母)。我检查是否 isalpha 然后将计数加一。然后我检查 isdigit 并添加到该计数。

最后我检查两个计数是否大于或等于 1(意味着它至少包含一位数字和一个字母)并返回 true。我知道计数不是最好的方法,但我只是想测试该方法,但它不起作用,我不确定我的逻辑哪里错了。

bool isDigitLetter::filter(string word) {
    int digit = 0;
    int letter = 0;
    if(word.empty()) {
        return false;
    }
    for(int i = 0; i < word.length(); i++) {
        if(!isalpha((unsigned char)word[i]) || !isdigit((unsigned char)word[i])) {
            return false;
        }
    }
    for(int x = 0; x < word.length(); x++) {
        if(isalpha((unsigned char)word[x])) {
                letter+=1;
        }
        if(isdigit((unsigned char)word[x])) {
            digit+=1;
        }
    }
    if(digit && letter>= 1) {
        return true;
    }
}

我在想也许可以使用 isalnum 但如果它包含任何一个但不检查它是否包含至少一个则返回 true。

最佳答案

bool isDigitLetter::filter(string word) {
    bool hasLetter = false;
    bool hasDigit = false;
    for (int i = 0; i < word.size(); i++) {
        if (isdigit(word.at(i))) { hasDigit = true; }
        if (isalpha(word.at(i))) { hasLetter = true; }
    }
    return (hasLetter && hasDigit);
} 

此解决方案删除了​​大量不必要的代码。

基本上,它遍历字符串并检查每个字符是字母还是数字。每次它看到一个,它都会更新 hasLetter/hasDigit 变量。如果两者都为真则返回真,否则返回假。

编辑:这个解决方案更快——如果它已经看到一个字母和一个数字,它会立即返回。

bool isDigitLetter::filter(string word) {
    bool hasLetter = false;
    bool hasDigit = false;
    for (int i = 0; i < word.size(); i++) {
        if (isdigit(word.at(i))) { hasDigit = true; }
        if (isalpha(word.at(i))) { hasLetter = true; }
        if (hasDigit && hasLetter) { return true; }
    }
    // we got here and couldn't find a letter and a digit
    return false;
} 

关于C++ 检查字符串是否包含至少 1 个数字和 1 个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48098173/

相关文章:

c++ - 如果在同一个范围内有同名的类和变量,如何指定类?

C++用户输入到字符串数组无限循环

c++ - 如何检查一个进程是否正在运行或在 linux 中从我的 main() 中的 pid 在 linux 中终止

c++ - 是我还是Boost Track SVN(Boost Geometry Extension Dissolve)的一部分无法编译?

C++:初始化列表+模板产生奇怪的错误

c++ - 无法使用 GLFW3 初始化 GLew

c++ - 在 xcode 4 中找不到文件

c++ - constexpr 重载

c++ - 我们应该在 std 命名空间中使用 C 函数吗?

c++ - 返回字符串的所有子字符串的递归函数