Problem Description
输入一个字符串,判断其是否是C的合法标识符。
Input
输入数据包含多个测试实例,数据的第一行是一个整数n,表示测试实例的个数,然后是n行输入数据,每行是一个长度不超过50的字符串。
Output
对于每组输入数据,输出一行。如果输入数据是C的合法标识符,则输出"yes",否则,输出“no”。
Sample Input
3 12ajf fi8x_a ff ai_2
Sample Output
no yes no
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2024
这个题目其实不难,我纠结了很久是因为我不知道怎么连续判断字符串第一位之后的其他字符都符合标识符的要求,然后输出!!!后面还是同学给了我答案,字符串中的每一个一旦符合要求就a++(a首先赋值为0),然后与字符串长度相比较,如果相同就输出“yes”
代码如下:
#include<iostream>
#include<string>
using namespace std;
int main()
{
int n,a,i;
string str;
while(cin>>n)
{
getchar();
while(n--)
{
getline(cin,str);
a=0;
if(str[0]=='_'||(str[0]>='A'&&str[0]<='Z')||(str[0]>='a'&&str[0]<='z'))
{
for(i=1;i<str.size();i++)
{
if(str[i]=='_'||(str[i]>='A'&&str[i]<='Z')||(str[i]>='a'&&str[i]<='z')||(str[i]>='0'&&str[i]<='9'))
{
a++;
}
}
if(a==str.size()-1)//i是从str[1]开始的
{
cout<<"yes"<<endl;
}
else
{
cout<<"no"<<endl;
}
}
else
{
cout<<"no"<<endl;
}
}
}
return 0;
}