HDU_2024 C语言合法标识符

只要弄懂什么事C语言的合法标识符就比较简单了,

C语言的合法标志符就是一串只能由字母、数字和下划线组成的字符串,

并且要以字母或下划线开头,

只要记住这个就OK了!^ ^

当然也看到了用#include <ctype.h> 的头文件,

然后以isalpha(int ch)函数判断是否为字母字符,

isalnum(int ch)函数判断是否为字母字符或数字,

运用这个方法会更简单,

把两种方法都贴出来了。

下面是自己编的最原始的代码:

#include <stdio.h>
#include <string>
#include <string.h>
#include <iostream>

using namespace std;

int islegal(char c)
{
 	if (c == '_')
 	    return 1;
    else if (c >= 'a' && c <= 'z')
        return 1;
    else if (c >= 'A' && c <= 'Z')
    	return 1;
    else if (c >= '0' && c <= '9')
    	return 1;
    else return 0;
}

int main()
{
	char c;
	islegal(c);
	int n;
	while (cin >> n)
	{
        getchar();
 	    for (int i = 0; i < n; i ++)
 	    {
		 	char str[100];
		 	gets (str);
		 	int len = strlen (str), flag = 1;
		 	for (int j = 0; j < len; j ++)
			{
				if (!(str[0] >= 'a' && str[0] <= 'z' || str[0] >= 'A' && str[0] <= 'Z' || str[0] == '_'))
				{
					flag = 0;
					break;
				}
				if (islegal(str[j]) == 0)
				{
					flag = 0;
					break;
				}	
			}
			
			if (flag == 0)
			   cout << "no" << endl;
			else cout << "yes" << endl; 
		}
    }
    system ("pause");
    return 0;
}

这个第二种比较简单的方法:

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值