user2226041
user2226041

Reputation: 15

How to check if parts of a single-string input are int or char?

I have to take a string i/p of length 15. First two letters should be alphabets, next 13 digits. Eg: AB1234567891234. How can I check if the first two are only alphabets and others are only digits?

Upvotes: 1

Views: 111

Answers (4)

praks411
praks411

Reputation: 1992

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

Upvotes: 0

Johnny Mnemonic
Johnny Mnemonic

Reputation: 3912

You can use the functions defined in the <cctype> header file like isalpha() and isdigit().

Upvotes: 1

perreal
perreal

Reputation: 97938

#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";

Upvotes: 6

user142019
user142019

Reputation:

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

Upvotes: 1

Related Questions