描述
给定一个不包含空白符的字符串,请判断是否是C语言合法的标识符号(注:题目保证这些字符串一定不是C语言的保留字)。
C语言标识符要求:
1.非保留字;
2.只包含字母、数字及下划线(“_”)。
3.不以数字开头。
格式
输入格式
一行,包含一个字符串,字符串中不包含任何空白字符,且长度不大于20。
输出格式
一行,如果它是C语言的合法标识符,则输出yes,否则输出no。
样例
输入样例
RKPEGX9R;TWyYcp
输出样例
no
限制
时间限制: 1000 ms
内存限制: 65536 KB
源码
这个题是基础题,但是粗心的我考虑不周全,冲上来开开心心的balabala写下这些:
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
char s[21];
int main()
{
int i,l,flag=0;
gets(s);
l=strlen(s);
if(s[0]>='0'&&s[0]<='9')
{
cout<<"no"<<endl;
return 0;
}
for(i=0;i<l;i++)
{
if(s[i]==' ')
{
cout<<"no"<<endl;
return 0;
}
else
{
if((s[i]=='_'||(s[i]>='A'&&s[i]<='Z')||(s[i]>='0'&&s[i]<='9')||(s[i]>='a'&&s[i]<='z')))
{
flag++;
}
else
{
flag=0;
}
}
}
if(flag!=0)
{
cout<<"yes"<<endl;
}
else
{
cout<<"no"<<endl;
}
return 0;
}
运行后没问题哈哈哈,但是去OJ里提交后只有90分,我就寻思着哪个案例过不了?DEBUG一下发现`
else
{
flag=0;
}
这一块真是罪魁祸首。。。。。。。
后来改正后成功 AC的代码如下(这是一开始想到的方法,有点笨笨的):
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
char s[21];
int main()
{
int i,l,flag=0;
gets(s);
l=strlen(s);
if(s[0]>='0'&&s[0]<='9')//开头就是数字那故事结束
{
cout<<"no"<<endl;
return 0;
}
for(i=0;i<l;i++)
{
if((s[i]=='_'||(s[i]>='A'&&s[i]<='Z')||(s[i]>='0'&&s[i]<='9')||(s[i]>='a'&&s[i]<='z')))//符合C的标示符要求咱们就有故事
{
flag++;
}
else
{
cout<<"no"<<endl;
return 0;
}
}
if(flag!=0)
{
cout<<"yes"<<endl;
}
else
{
cout<<"no"<<endl;
}
return 0;
}