2013-03-29 60 views
1

我得带一个字符串长度为15的字符串。前两个字母应该是字母,后面的13位数字。例如:AB1234567891234。我如何检查前两个字母是否只有字母,其他字母只有数字?如何检查单个字符串输入的部分是int还是char?

+2

['的std :: is_alpha'](http://en.cppreference.com/w/cpp/string/byte/isalpha),['的std :: is_digit'] (http://en.cppreference.com/w/cpp/string/byte/isdigit) –

回答

6
#include <regex> 
const std::regex e("^[a-zA-Z][a-zA-Z][0-9]{13}$"); 
std::string str = "ab1234567890123"; 
if (std::regex_match (s,e)) 
    std::cout << "string object matched\n"; 
1
#include <cctype> 

bool is_correct(std::string const& s) { 
    if (s.size() != 15) return false; 
    if (!std::isalpha(string[0]) || !std::isalpha(string[1])) 
     return false; 
    for (std::size_t i = 2; i < 13; ++i) { 
     if (!std::isdigit(string[i])) return false; 
    } 
    return true; 
} 
0
#include<iostream> 
    #include<string> 

    int main(int argc, char *argv[]) 
    { 
    std::string n_s = "AB1234567896785"; 
    bool res = true; 
    std::cout<<"Size of String "<<n_s.size()<<n_s.length()<<std::endl; 
    int i = 0, th = 2; 

    while(i < n_s.length()) 
     { 
     if(i < th) 
     { 
      if(!isalpha(n_s[i])) 
      { 
      res = false; 
      break; 
      } 
     } 
     else 
     { 
      if(!isdigit(n_s[i])) 
      { 
      res = false; 
      break; 
      } 
     } 
     i++; 
    } 
    if(res) 
    { 
     std::cout<<"Valid String "<<std::endl; 
    } 
    else 
    { 
     std::cout<<"InValid Strinf "<<std::endl; 
    } 
     return 0; 
    } 
相关问题