日期:2009-10-20  浏览次数:20427 次

作为程序设计人员经常会遇到这样的情况,需要将某个指定的字符串表达式转换为算术表达式并计算其结果.使用Delphi的朋友可以在网上获取第三方控件来实现,而.Net框架类库并没有相关的处理类,正好在前不久的给一所大学开发的Web应用中也需要实现相关的处理.就抽空写了一个相关的处理类(实现了大部分的算术运算操作,需要其他运算可以在现有基础上扩展),现将部分代码贴出共大家参考,希望能够在交流中进步、互助中学习、探讨中深入:


//EnumExpress

using System;

namespace ExpressionTest
{
/// <summary>
/// EnumExpress 的摘要说明。
/// </summary>
public enum EnumExpress
{
Add,//加号
Dec,//减号
Mul,//乘号
Div,//除号
Sin,//正玄
Cos,//余玄
Tan,//正切
ATan,//余切
Sqrt,//平方根
Pow,//求幂
None,//无
}
}


//ExpressDeal

using System;

namespace ExpressionTest
{
/// <summary>
/// ExpressDeal 的摘要说明。
/// </summary>
public class ExpressDeal
{
static ExpressDeal()
{

}
private double CalculateExpress(string strExpression)
{

string strTemp="";
string strTempB="";
string strOne="";
string strTwo="";
double ReplaceValue=0;
while (strExpression.IndexOf("+")!=-1 || strExpression.IndexOf("-")!=-1
|| strExpression.IndexOf("*")!=-1 || strExpression.IndexOf("/")!=-1)
{
if (strExpression.IndexOf("*")!=-1)
{
strTemp=strExpression.Substring(strExpression.IndexOf("*")+1,strExpression.Length-strExpression.IndexOf("*")-1);
strTempB=strExpression.Substring(0,strExpression.IndexOf("*"));

strOne=strTempB.Substring(GetPrivorPos(strTempB)+1,strTempB.Length-GetPrivorPos(strTempB)-1);

strTwo=strTemp.Substring(0,GetNextPos(strTemp));

ReplaceValue=Convert.ToDouble(GetExpType(strOne))*Convert.ToDouble(GetExpType(strTwo));

strExpression=strExpression.Replace(strOne+"*"+strTwo,ReplaceValue.ToString());
}
else if (strExpression.IndexOf("/")!=-1)
{
strTemp=strExpression.Substring(strExpression.IndexOf("/")+1,strExpression.Length-strExpression.IndexOf("/")-1);
strTempB=strExpression.Substring(0,strExpression.IndexOf("/"));

strOne=strTempB.Substring(GetPrivorPos(strTempB)+1,strTempB.Length-GetPrivorPos(strTempB)-1);


strTwo=strTemp.Substring(0,GetNextPos(strTemp));


ReplaceValue=Convert.ToDouble(GetExpType(strOne))/Convert.ToDouble(GetExpType(strTwo));

strExpression=strExpression.Replace(strOne+"/"+strTwo,ReplaceValue.ToString());
}
else if (strExpression.IndexOf("+")!=-1)
{
strTemp=strExpression.Substring(strExpression.IndexOf("+")+1,strExpression.Length-strExpression.IndexOf("+")-1);
strTempB=strExpression.Substring(0,strExpression.IndexOf("+"));

strOne=strTempB.Substring(GetPrivorPos(strTempB)+1,strTempB.Length-GetPrivorPos(strTempB)-1);

strTwo=strTemp.Substring(0,GetNextPos(strTemp));

ReplaceValue=Convert.ToDouble(GetExpType(strOne))+Convert.ToDouble(GetExpType(strTwo));

strExpression=strExpression.Replace(strOne+"+"+strTwo,ReplaceValue.ToString());
}
else if (strExpression.IndexOf("-")!=-1)
{
strTemp=strExpression.Substring(strExpression.IndexOf("-")+1,strExpression.Length-strExpression.IndexOf("-")-1);
strTempB=strExpression.Substring(0,strExpression.IndexOf("-"));

strOne=strTempB.Substring(GetPrivorPos(strTempB)+1,strTempB.Length-GetPrivor