HDU-2024 C语言合法标识符

来源:互联网 发布:p.f candle co知乎 编辑:程序博客网 时间:2024/06/05 08:48

HDU-2024 C语言合法标识符

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

C语言标识符的要求:1、第一个字符必须为字母或者_ 2、必须由字母或者数字或者下划线_组成。

代码

#include <stdio.h>int hf(char s[55]){   int count=0;    if((s[0]>='A'&&s[0]<='Z')||(s[0]>='a'&&s[0]<='z')||s[0]=='_')    {      for(int i=1;;i++)      {        if((s[i]>='0'&&s[i]<='9')||(s[i]>='A'&&s[i]<='Z')||(s[i]>='a'&&s[i]<='z')||s[i]=='_')count=1;        else if(s[i]=='\0') break;         else           {            count=0;break;          }       }    }    return count;   }int main(){    int n;    scanf("%d",&n);    getchar();//这里如果没有,那么回车键会被存放在储存器中,不会被清除,进行到下面的步骤时,gets会把回车键读取,也就是空的,即读取了一个空格 。    int a[n];    char s[55];    for(int j=0;j<n;j++)    {        gets(s);//这里不能用scanf,因为scanf以空格键作为结束,而gets以回车键作为结束。         a[j]=hf(s);         }    for(int j=0;j<n;j++)    {        if(a[j]==0)printf("no\n");        if(a[j]==1)printf("yes\n");    }    return 0;}

简单方法:
头文件为ctype.h
1. isalpha判断字符ch是否为英文字母,当ch为英文字母a-z或A-Z时,返回非零值(不一定是1),否则返回零
2. isalnum判断字符变量c是否为字母或数字,当c为数字0-9或字母a-z及A-Z时,返回非零值,否则返回零。

#include <ctype.h>  #include <stdio.h>  int main()  {      int n, d, i;      char sym[64];      scanf("%d%*c", &n);      while (n--)      {          gets(sym);          if (sym[0] != '_' && !isalpha(sym[0]))          {              puts("no");              continue;          }          for (d = i = 1 ; sym[i] ; i++)          {              if (!isalnum(sym[i]) && sym[i] != '_')              {                  d = 0;                  break;              }          }          puts(d ? "yes" : "no");      }      return 0;  } 

主要函数简介

isalpha
函数名称: isalpha
函数原型: int isalpha(char ch);
函数功能: 检查ch是否是字母.
函数返回: 是字母返回非0(在vs2015中为2) ,否则返回 0.

isdigit
函数名称: isdigit
函数原型: int isdigit(char ch);
函数功能: 检查ch是否是数字(0-9)
函数返回: 是返回非0,否则返回0

islower
函数名称: islower
函数原型: int islower(int ch);
函数功能: 检查ch是否小写字母(a-z)
函数返回: 是返回非0,否则返回0

isupper
函数名称: isupper
函数原型: int isupper(int ch);
函数功能: 检查ch是否是大写字母(A-Z)
函数返回: 是返回非0,否则返回0

tolower
函数名称: tolower
函数原型: int tolower(int ch);
函数功能: 将ch字符转换为小写字母
函数返回: 返回ch所代表的字符的小写字母

toupper
函数名称: toupper
函数原型: int toupper(int ch);
函数功能: 将ch字符转换成大写字母
函数返回: 与ch相应的大写字母

isalnum
函数名称: isalnum
函数原型: int isalnum(int ch);
函数功能: 检查ch是否是字母或数字
函数返回: 是字母或数字返回非0,否则返回0

isspace
函数名称: isspace
函数原型: int isspace(int ch);
函数功能: 检查ch是否是空格符和跳格符(控制字符)或换行符
函数返回: 是返回非0,否则返回0
参数说明:

原创粉丝点击