简体   繁体   中英

In C, how do I check if a String contains 2 digits, 1 letter and 4 digits?

In the method I've tried this:

int 1, 2, 4, 5, 6, 7;
char 3;
char display[10];

scanf("%d%d%c%d%d%d%d", &1, &2, &3, &4, &5, &6, &7);
display = {1, 2, 3, 4, 5, 6, 7};

But I get errors everywhere and it doesn't work.

Presumably in that order?

Walk the string a char at a time and use isdigit() isalpha() to check each one.
Or just do:

char test[] = "12B3456";

if ( (strlen(test)>6) &&
     isdigit(test[0]) && 
     isdigit(test[1]) &&
     isalpha(test[2]) && 
     isdigit(test[3]) &&
     isdigit(test[4]) &&
     isdigit(test[5]) &&
     isdigit(test[6]) ) 
{
   // valid
}

First of all, in C, variable names can't start with a number, or be a number for that matter. So the declaration of int 1,2,3,4,5,6,7 will not compile, as well as char 3;

Here's a sample of how you could do it assuming the input is a null terminated string:

int matches(char *input){
    int i;

    /* This array contains 1 in places where a digit is expected */
    char expected_digits[] = {1,1,0,1,1,1,1};

    for(i = 0 ; input[i] != 0 && i < 7; i++){
        if(expected_digits[i] == 1){
            if(!isdigit(input[i])){
                 return 0;
            }
        }
        else{
            if(!isalpha(input[i]))
            {
                 return 0;
            }
        }
     }

     if(i == 7) {
         /* We reached the end of the input string and all its places matched */
         return 1;
     }
     else{
         return 0;
     }
}

Not the best piece of code, but should do the trick. And it should compile with a C compiler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM