【题目链接】
ybt 1134:合法C标识符
OpenJudge NOI 1.7 06:合法C标识符
【题目考点】
1. 字符判断
- 判断一个字符c是不是数字:
c >= '0' && c <= '9'
或isdigit(c)
- 判断一个字符c是不是大写字母:
c >= 'A' && c <= 'Z'
或isupper(c)
- 判断一个字符c是不是小写字母:
c >= 'a' && c <= 'z'
或islower(c)
- 判断一个字符c是不是字母:
c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z'
或isalpha(c)
- 判断一个字符c是不是字母或数字:
c >= '0' && c <= '9' || c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z'
或isalnum(c)
【解题思路】
- 已知输入的字符串不会是C语言关键字
- 先判断第一个字符是不是数字,如果是,则该字符串不是合法标识符,程序结束。
- 判断后面每一个字符,如果出现不是字母数字下划线的字符,那么该字符串不是合法标识符,程序结束。
- 如果运行到了这里,那么字符串中每一个字符都是合法的,该字符串是一个合法标识符。
【题解代码】
解法1:使用字符的区间
通过判断字符的ASCII码在哪个区间中,来确定该字符是字母还是数字
#include <bits/stdc++.h>
using namespace std;
int main()
{
char s[25];
cin>>s;
if(s[0] >= '0' && s[0] <= '9')//如果第一个字符是数字
{
cout<<"no";
return 0;
}
int len = strlen(s);
for(int i = 0; i < len; ++i)
{
if(!(s[i] >= '0' && s[i] <= '9' ||
s[i] >= 'a' && s[i] <= 'z' ||
s[i] >= 'A' && s[i] <= 'Z' ||
s[i] == '_'))//如果出现不满足要求的字符
{
cout<<"no";
return 0;
}
}
cout<<"yes";
return 0;
}
解法2:使用<ctype>中的函数
#include <bits/stdc++.h>
using namespace std;
int main()
{
char s[25];
cin>>s;
if(isdigit(s[0]))//如果第一个字符是数字
{
cout<<"no";
return 0;
}
int len = strlen(s);
for(int i = 0; i < len; ++i)
{
if(!(isalnum(s[i]) || s[i] == '_'))//如果出现不满足要求的字符
{
cout<<"no";
return 0;
}
}
cout<<"yes";
return 0;
}