C# .NET - ...How to do ? - Asked By shah zeb on 21-Nov-11 12:36 AM

Hi,
if a string contains
str testStr = "10+90/4*34 -2";
and i need its mathematical output what should be done?
Regards,
Shah

Riley K replied to shah zeb on 21-Nov-11 12:44 AM

If you want to validate a string containing "2+1-(3*2)+8/2" in C#,
you're either going to have to write a math expression parser/evaluator,
or use the CodeDom support to compile the code to C# (with its syntax
restrictions) and call the code directly.

Apart from a couple of expression evaluators:
http://www.codeplex.com/Flee
http://www.codeplex.com/LazyParser

You could also create a DataTable, add a DataColumn and exploit it's Expression property

string expression = "2+1-(3*2)+8/2";

DataTable dataTable = new DataTable();

dataTable.Columns.Add("col1", typeof(int), expression);

dataTable.Rows.Add(new object[] { });

Console.WriteLine(dataTable.Rows[0][0]);

Regards

Reena Jain replied to shah zeb on 21-Nov-11 01:49 AM

Hi,

First you call the static Initialise, the pass your string to EvaluateStringAsDouble() and it gives you the result back as a double.

check this

usingSystem;

usingMicrosoft.JScript;

usingMicrosoft.JScript.Vsa;

namespaceVPDBUtils

{

publicclassJScriptEvaluator

{

privatestaticVsaEngine vsaEngine;

publicstaticvoidInitialize()

{

vsaEngine = VsaEngine.CreateEngine();

}

publicstaticvoidClose()

{

if(vsaEngine != null)

{

vsaEngine.Close();

}

}

privatestaticobjectEvaluateString(stringsStringToEvaluate)

{

returnEval.JScriptEvaluate(sStringToEvaluate, vsaEngine);

}

internalstaticdoubleEvaluateStringAsDouble(stringsStringToEvaluate)

{

returnSystem.Convert.ToDouble(EvaluateString(sStringToEv aluate));

}

}

}

here is the link for more help
http://www.codeproject.com/KB/vb/math_expression_evaluator.aspx

Suchit shah replied to shah zeb on 21-Nov-11 04:53 AM

The Matematical Output of this you get by using following steps :
1. Define Your StringString testStr = "10+90/4*34 -2";
2. Pass your string in this Expression ( This is the main line which perform operation)