/*
* Name: identifier.c
* Author: x-bit, at www.patching.net, AllRights Reserved.
* Description: 输入一串字符,判断该字符串是不是合法的C语言标识符。
* Date: 09-05-2004
* Compile environment: win2k+vc6下调试通过
*
*/
#include <stdio.h>
int identf(char *str);
int isKey(char *str);
int x_strcmp(char *si, char *di);
int main()
{
char buffer[256];
printf("Enter a string: ");
gets(buffer);
if(identf(buffer))
puts("合法的标识符");
else
puts("非法的标识符");
return 0;
}
/**************************************************************************/
int identf(char *str)
{
int flag=0;
char *p=str;
/*判断第一个字符是否符合*/
if((*str>='a' && *str<='z') || (*str>='A' && *str<='Z') || *str=='_')
{
flag=1;
str++;
}
/*从第二个字符开始遍历判断*/
while(*str && flag)
{
if((*str>='a' && *str<='z') || (*str>='A' && *str<='Z') || *str=='_'
|| (*str>='0' && *str<='9'))
{
flag=1;
str++;
}
else
flag=0;
}
/*判断是不是关键字*/
if(flag)
flag=isKey(p);
return flag;
}
/*****************************是不是关键字*******************************/
int isKey(char *str)
{
char *keyword[]={"auto", "break", "case", "char", "const", "continue", "default",
"do", "double", "else", "enum", "extern", "float", "for", "goto",
"if", "int", "long", "register", "return", "short", "signed",
"sizeof", "static", "struct", "switch", "typedef", "union", "unsigned",
"void", "volatile", "while"};
int i, flag=1;
for(i=0; i<32; i++)
{
if(x_strcmp(str, keyword[i])==0)
{
flag=0;
break;
}
}
return flag;
}
/*****************************字符串比较函数*******************************/
/* 为了练技术,自己写了一个strcmp() */
int x_strcmp(char *si, char *di)
{
while(*si && *di && *si==*di)
{
si++;
di++;
}
return *si-*di;
}
本文地址:http://com.8s8s.com/it/it26747.htm