簡體   English   中英

C ++檢查字符串是否至少包含1位數字和1個字母

[英]C++ Check if String contains atleast 1 digit and 1 letter

我試圖在返回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但是如果包含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,則返回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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM