從頭開始搭建算術表達式解析器,第三部分

這一部分是比較貼近實用的,目的是將字符串劃分而且識別爲一個個的表達式元件(Atom),使用正則表達式會很簡單,可是,怎麼說來着,我們此次要求的不高,只要實現就好,因此額外的支持我都沒有使用(好比hash和正則神馬的,使用的只有標準C庫) 正則表達式

int GetFromNumber(char *str,Atom *ele)
{
	int i=0;
	ele->type=Is_Value;
	ele->data=(myFac*)new myValue;
	ele->data->vlu=atof(str);
	while(str[i]>='0' && str[i]<='9')i++;
	if(str[i]=='.')
	{
		if(str[i+1]>='0' && str[i+1]<='9')i++;else return i;
		while(str[i]>='0' && str[i]<='9')i++;
	}
	if(str[i]=='e')
	{
		if((str[i+1]=='-' || str[i+1]=='+')&&(str[i+2]>='0' && str[i+2]<='9'))i+=2;else if(str[i+1]>='0' && str[i+1]<='9')i++;else return i;
		while(str[i]>='0' && str[i]<='9')i++;
	}
	return i;
}
int GetFromString(char *str,Atom *ele)
{
	char u[8];
	int i=0;
	while((str[i]>='0' && str[i]<='9')||(str[i]>='a' && str[i]<='z')||(str[i]>='A' && str[i]<='Z')||str[i]=='_')(u[i]=str[i],i++);
	u[i]='\0';
	if(GetParam(u))
	{
		ele->type=Is_Param;
		ele->data=(myFac*)new myParam;
		ele->data->adr=GetParam(u);
	}
	else if(GetFun1p(u))
	{
		ele->type=Is_Fun1p;
		ele->data=(myFac*)new myFun1p;
		ele->data->fc1=GetFun1p(u);
	}
	else if(GetFun2p(u))
	{
		ele->type=Is_Fun2p;
		ele->data=(myFac*)new myFun2p;
		ele->data->fc2=GetFun2p(u);
	}
	else i=0;
	return i;
}
int GetFromOthers(char *str,Atom *ele)
{
	char u[3];
	int i,j;
	switch(str[0])
	{
		case '+':
		case '-':
		case '*':
		case '/':
		case '>':
		case '<':
		case '=':
		case '!':
			u[0]=str[0];
			if(str[1]=='=')(u[1]='=',u[2]='\0';,i=2);else (u[1]='\0',i=1);
		break;
		case '&':
			u[0]=u[1]='&';u[2]='\0';
			if(str[1]=='&')i=2;else i=1;
		break;
		case '|':
			u[0]=u[1]='|';u[2]='\0';
			if(str[1]=='|')i=2;else i=1;
		break;
		case '$':
		case '@':
		case '#':
		case '(':
		case ',':
		case ')':
			u[0]=str[0];u[1]='\0';
			i=1;
		break;
		default:
			return 0;
		break;
	}
	j=GetOpert(u);
	switch(j)
	{
		case 1:
			ele->type=Is_Setvr;
			ele->data=(myFac*)new mySetvr;
			strcpy(ele->data->opr,u);
		break;
		case 2:
		case 3:
		case 4:
		case 5:
			ele->type=Is_Opr2p;
			ele->data=(myFac*)new myOpr2p;
			strcpy(ele->data->opr,u);
		break;
		case 6:
			ele->type=Is_Opr1p;
			ele->data=(myFac*)new myOpr1p;
			strcpy(ele->data->opr,u);
		break;
		default:
			switch(u[0])
			{
				case '(':
					ele->type=Is_Lquot;
					ele->data=new myFac;
					strcpy(ele->data->opr,u);
				break;
				case ',':
					ele->type=Is_Comma;
					ele->data=new myFac;
					strcpy(ele->data->opr,u);
				break;
				case ')':
					ele->type=Is_Rquot;
					ele->data=new myFac;
					strcpy(ele->data->opr,u);
				break;
				default:break;
			}
		break;
	}
	return i;
}
int GetAtom(char *str,Atom *ele)
{
	char c=*str;
	if(c>='0' && c<='9')
	{
		return GetFromNumber(str,ele);
	}
	else if((c>='a' && c<='z')||(c>='A' && c<='Z')||(c=='_'))
	{
		return GetFromString(str,ele);
	}
	else
	{
		return GetFromOthers(str,ele);
	}
	return 0;
}
相關文章
相關標籤/搜索