日期:2014-05-20  浏览次数:20837 次

用Java(C++)做一个词法分析器,急用!!!
各位大侠,谁能用Java或者C++帮小弟做一个词法简单的分析器,急用,谢谢了!

------解决方案--------------------
《编译原理》的题目吧,还是自个弄吧

如果是实际项目,可以用antlr,现成的词法、语法解析工具
------解决方案--------------------
#include <iostream>
#include <ctype.h>
#include <fstream>
#include <string.h>
#include <malloc.h>
using namespace std;
ifstream fp("example.c",ios::in);
char cbuffer;
char *key[14]={"if","else","for","while","do","return","break","continue","int","void"
,"main","const","printf","char"}; //关键字
char *border[10]={ "," , ";" , "{" , "}" , "(" , ")" ,"//","\"","[","]"}; //分界符
char *arithmetic[6]={"+" , "-" , "*" , "/" , "++" , "--"}; //运算符
char *relation[7]={"<" , "<=" , "=" , ">" , ">=" , "==" ,"!="}; //关系运算符
char *lableconst[80]; //标识符
int lableconstnum=0; //统计常数和标识符数量 
int constnum=40;
int linenum=1;
int search(char searchchar[],int wordtype)
{
 int i=0,t=0;
 switch (wordtype)
 {
 case 1:
{ for (i=0;i<=13;i++) //关键字
{
if (strcmp(key[i],searchchar)==0)
return(i+1);
}
return(0);}
 case 2:
{
for (i=0;i<=9;i++) //分界符
{
if (strcmp(border[i],searchchar)==0)
return(i+1);

return(0);

 case 3:
{
for (i=0;i<=5;i++) //运算符
{
if (strcmp(arithmetic[i],searchchar)==0)
return(i+1);
}
return(0);
}
 case 4:
{
for (i=0;i<=6;i++) //关系运算符
{
if (strcmp(relation[i],searchchar)==0)
return(i+1);
}
return(0);
}
 case 5:
{
for (t=40;t<=constnum;t++) //常数
{
if (strcmp(searchchar,lableconst[t])==0)//判断该常数是否已出现过 
return(t+1);

lableconst[t-1]=(char *)malloc(sizeof(searchchar));//为新的元素分配内存空间
strcpy(lableconst[t-1],searchchar);//为数组赋值lableconst指针数组名
constnum++; //常数个数自加
return(t);
}
 case 6:
{
for (i=0;i<=lableconstnum;i++)
{
if (strcmp(searchchar,lableconst[i])==0) //判断标识符是否已出现过
return(i+1);
}
lableconst[i-1]=(char *)malloc(sizeof(searchchar));
strcpy(lableconst[i-1],searchchar);
lableconstnum++; //标识符个数自加
return(i);
}
 default:cout<<"错误!";
 }
}
char alphaprocess(char buffer) //字符处理过程
{
 int atype;
 int i=-1;
 char alphatp[20];
 while ((isalpha(buffer))||(isdigit(buffer))) //这两个函数分别是判字符和判数字函数
 {
alphatp[++i]=buffer;
fp.get(buffer);
 }
 alphatp[i+1]='\0';//在末尾添加字符串结束标志
 if (atype=search(alphatp,1))
cout<<"linenum: "<<linenum<<" String= "<<alphatp<<"\t\t\t"<<"关键字"<<endl;
 else
 {
atype=search(alphatp,6); //标识符
cout<<"linenum: "<<linenum<<" String= "<<alphatp<<"\t\t\t"<<"标识符"<<endl;