码迷,mamicode.com
首页 > 其他好文 > 详细

私人定制-词法分析

时间:2016-09-30 14:55:34      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

私人定制词法分析,能够在输入一整段句子时准确地进行词法分析,并提供种别码表。

通过定义数组循环不断读入与分析单词。

先判断单词是否为数字,如是标志符再进一步判断是关键字、界符还是标识符。

每次读完单词执行一次getchar()后重复循环,当输出##时退出循环。

图片、源代码如下:

#include<stdio.h>
#include<string.h>
#define Max 100
int JdujeNumber(char Words[],int i,int N);
int JdujeKeywords(char Words[]);
char *table[Max][1]={"#","begin","if","then","while","do","end","l(l|d)*","dd*","+","-","*","/",":",":=","<","<=","<>",">",">=","=",";","(",")"};
char Words[Max];
main()
{
    int j,i=0,key;
    printf("\n各种单词符号对应的种别码\n");
    for(j=0;j<23;j++)
    {
        printf("%s\t%d\t\t",table[j][0],j);
        if(j%2==0)
            printf("\n");
    }
    printf("请输入:(输入##代表结束)");
    do
    {
        scanf("%s",Words);
        if(strcmp(Words,"##")==0)
        break;
        j=JdugeNumber(Words,i,strlen(Words));
        if(j==1)
            printf("%s\t是数字\n",Words);
        else if(j==0)
            {
                key=JdujeKeywords(Words);
                if(key>=0&&key<=7)
                {
                    printf("%s\t是关键字\n",Words);
                }
                else if(key>7&&key<=22)
                {
                    printf("%s\t是界符\n",Words);
                }
                else
                {
                    printf("%s\t是标识符\n",Words);
                }
            }
            getchar();
    }while(1);
    printf("程序结束!");
}
int JdugeNumber(char Words[],int i,int N)
{
    if(i==N)
        return 1;
    if(Words[i]>47&&Words[i]<58)
    {
        JdugeNumber(Words,i+1,N);
    }
    else
        return 0;
}
int JdujeKeywords(char Words[])
{
    int i;
    for(i=0;i<23;i++)
    {
        if(strcmp(Words,table[i][1])==0)
            return i;
    }
    return -1;
}

技术分享

 

私人定制-词法分析

标签:

原文地址:http://www.cnblogs.com/ChalingStreet/p/5923493.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!