Mar*_*lor 12 c# string math evaluation parsing
有没有一种简单的方法来评估字符串
"(4+8)*2"
,以便你得到24的int值?
或者还有很多工作要做到这一点......?
Ric*_*ell 38
其他人添加了这个,然后它被删除了.我认为这很酷,因为不需要第三方库.
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Evaluate("(4+8)*2"));
Console.ReadKey();
}
public static double Evaluate(string expression)
{
DataTable table = new DataTable();
table.Columns.Add("expression", typeof(string), expression);
DataRow row = table.NewRow();
table.Rows.Add(row);
return double.Parse((string)row["expression"]);
}
}
man*_*lds 19
使用Ncalc:
Expression e = new Expression("(4+8)*2");
Debug.Assert(24 == e.Evaluate());
Run Code Online (Sandbox Code Playgroud)
此外,这个问题之前已经被问过并且有一些有趣的答案,包括Ncalc:评估字符串"3*(4 + 2)"yield int 18