c# - 解析表达式的最佳方法 - 多个变量
问题描述
我有一种情况,我需要解析多个 n 个相关字段(不想评估):
string exp1 = "10";
string exp2 = "20";
string exp3= "exp1 + exp2 + 30";
string exp4 = "exp5 - exp3";
string exp5 = "exp3 / 10";
Dictionary<string,string> expressions = new Dictionary<string,string>();
expressions.Add("exp1", exp1);
expressions.Add("exp2", exp2);
expressions.Add("exp3", exp3);
expressions.Add("exp4", exp3);
expressions.Add("exp5", exp5);
现在我们要遍历所有表达式字段并用实际值解析表达式(也应该应用 Bodmas)。所以,解析后,我们希望下面作为输出:
exp1 = "10";
exp2 = "20";
exp3= "10 + 20 + 30";
exp4 = "((10 + 20 + 30 )/10) - (10+ 20 + 30)";
exp5 = "(10 + 29 + 30)/ 10";
我应该在这里使用什么数据结构来使用通用方式解析它?会是二叉树、图表、表达式树吗?
解决方案
编码
using System.Collections.Generic;
using Microsoft.VisualBasic; //the code was written in VB and converted. make appropriate changes if you don't want to use this namespace
class Exp
{
private Dictionary<string, string> AllExpressions = new Dictionary<string, string>();
public void Add(string name, string value)
{
AllExpressions.Add(name, value);
}
public string ValueOf(string name)
{
var parts = Strings.Split(AllExpressions[name]);
for (int i = 0; i <= parts.Length - 1; i++)
{
if (AllExpressions.ContainsKey(parts[i]))
{
var partVal = ValueOf(parts[i]);
parts[i] = Information.IsNumeric(partVal) ? partVal : $"({partVal})";
}
}
return Strings.Join(parts);
}
}
用法
Exp myExp = new Exp();
myExp.Add("exp1", "10");
myExp.Add("exp2", "20");
myExp.Add("exp3", "exp1 + exp2 + 30");
myExp.Add("exp4", "exp5 - exp3");
myExp.Add("exp5", "exp3 / 10");
// Test to see if we can get correct values
Console.WriteLine(myExp.ValueOf("exp1"));
Console.WriteLine(myExp.ValueOf("exp2"));
Console.WriteLine(myExp.ValueOf("exp3"));
Console.WriteLine(myExp.ValueOf("exp4"));
Console.WriteLine(myExp.ValueOf("exp5"));
结果
10
20
10 + 20 + 30
((10 + 20 + 30) / 10) - (10 + 20 + 30)
(10 + 20 + 30) / 10
推荐阅读
- javascript - 您如何垂直列出字符串输出并相应地编号?
- php - 为什么Controller Codeigniter中没有处理返回后的流程
- javascript - 如何修复“TypeError:app.use() 需要中间件函数”?
- python - 在 Keras 训练期间动态更改损失函数,无需重新编译优化器等其他模型属性
- vba - 如何从 excel 工作簿中获取价值以在 Web 表单保管箱中查找内容
- spring - 访问此资源需要 Spring OAuth2 完整身份验证
- javascript - 如何在 javascript 中访问该数组
- go - 如何在redis golang中将键值对传递给MSet?
- node.js - Cognito 登录 MFA 短信验证问题
- java - 分配给在方法中声明的类变量,没有实例化对象