An identifier is a sequence of characters. A valid identifier can contain only upper and lower case alphabetic characters, underscore and digits, and must begin with an alphabetic character or an underscore. Given a list of chararcter sequences, write a program to check if they are valid identifiers.
For each of the N lines, output "Yes" (without quote marks) if the character sequence contained in that line make a valid identifier; output "No" (without quote marks) otherwise.
7 ValidIdentifier valid_identifier valid_identifier 0 invalid identifier 1234567 invalid identifier adefhklmruvwxyz12356790 -.,:;!?'"()[]ABCDGIJLMQRSTVWXYZ
Yes Yes Yes No No No No
分析:该题是判断字符串是否为有效标识符,标识符的要求是:
1、字符串内只能由数字,字符,下划线
2、数字不能打头
代码如下:
#include <stdio.h> #include <string.h> char str[1005]; int check() { int i; if(str[0]>='0' && str[0]<='9') return 0; else { int len=strlen(str); for(i=0;i<len;i++) { if(!(str[i]>='0' && str[i]<='9' || str[i]>='a' && str[i]<='z' || str[i]>='A' && str[i]<='Z' || str[i]=='_')) return 0; } } return 1; } int main() { int T; scanf("%d%*c",&T); while(T--) { memset(str,0,sizeof(str)); gets(str); if(check()) printf("Yes\n"); else printf("No\n"); } return 0; }