在C中,如何检查字符串是否包含2位数字,1个字母和4个数字?

时间:2010-03-23 22:46:35

标签: c string arrays char

在方法中我试过这个:

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

但我到处都是错误而且无效。

2 个答案:

答案 0 :(得分:4)

大概是按顺序?

一次将字符串作为字符串,并使用isdigit()isalpha()来检查每个字符串。
或者只是做:

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
}

答案 1 :(得分:2)

首先,在C中,变量名不能以数字开头,或者是数字。因此,int 1,2,3,4,5,6,7的声明将不会编译,以及char 3;

以下是假设输入为空终止字符串的方法示例:

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

不是最好的代码,但应该做到这一点。它应该用C编译器编译。