2017-02-26 114 views
-3

我需要創建一個函數來檢查我作爲參數發送的字符串是否具有前4個字符作爲字母,最後3個是數字,並且它只有7個字符。我將如何編碼此功能?如何檢查字符串是否有一定數量的字母和數字?

+2

可以使用正則表達式:'[A-Za-z] {4} [0-9] {3}' – Brandon

+0

還沒有在我的class y中學過正則表達式et,主要必須使用基本的東西,比如包含在字符串庫中的東西。 –

+0

'std :: string :: length()'檢查長度是7,'std :: count_if()'檢查一個字符範圍包含預期的字母數和字母數。或者使用正則表達式庫。 –

回答

1

最簡單的解決方案將是循環通過串檢查每個個性,例如:

#include <string> 
#include <cctype> 

bool is4LettersAnd3Digits(const std::string &s) 
{ 
    if (s.length() != 7) 
     return false; 

    for (int i = 0; i < 4; ++i) { 
     if (!std::isalpha(s[i])) 
      return false; 
    } 

    for (int i = 4; i < 7; ++i) { 
     if (!std::isdigit(s[i])) 
      return false; 
    } 

    return true; 
} 

或者:

#include <string> 
#include <algorithm> 
#include <cctype> 

bool is4LettersAnd3Digits(const std::string &s) 
{ 
    return (
     (s.length() == 7) && 
     (std::count_if(s.begin(), s.begin()+4, std::isalpha) == 4) && 
     (std::count_if(s.begin()+4, s.end(), std::isdigit) == 3) 
    ); 
} 

或者,如果使用C++ 11或更高:

#include <string> 
#include <algorithm> 
#include <cctype> 

bool is4LettersAnd3Digits(const std::string &s) 
{ 
    if (
     (s.length() == 7) && 
     std::all_of(s.begin(), s.begin()+4, std::isalpha) && 
     std::all_of(s.begin()+4, s.end(), std::isdigit) 
    ); 
} 
+0

我會用'std :: all_of'替換'std :: count_if'。 – lisyarus

+0

@lisyarus'std :: all_of()'在C++ 11中是新的。早期版本中存在'std :: count_if()'。不過,我已經更新了我的答案。 –

+0

儘管我完全理解C++ 11不存在的環境,但假設當前C++語言的官方標準默認爲C++ 14,這聽起來是合乎邏輯的。如果必須使用舊版本,則應在問題中明確說明。 除此之外,很好的答案! – lisyarus

相關問題