2017-02-26 77 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

相关问题