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

C++ Check if String contains atleast 1 digit and 1 letter

本文关键字:数字 包含 字符串 检查 是否 C++      更新时间:2023-10-16

我正在尝试在返回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变量。然后,如果两者都为真,则返回 true,否则返回 false。

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

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;
} 

它应该是这样的:

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;
        }
    }
    return ((digit > 0) && (letter > 0));
}

您的问题出在以下行上:

if(digit && letter>= 1)

将其更改为:

if(digit >=1 && letter>= 1)