C# 字符串函数计算
仅供参考:
#region 字符串函数计算 /// <summary> /// 字符串函数运算 /// 格式1:@函数名(参数1,参数2...) /// 格式2:@函数名(参数1,参数2...)+@函数名(参数1,参数2...)-@函数名(参数1,参数2...).... /// </summary> /// <param name="str"></param> /// <returns></returns> private decimal StringToFunction(string str) { decimal result = 0; //是否带有运算符 if (Regex.IsMatch(str, @"[\+|\-|\*|\/]")) { //替换所有运算符,方便分析函数(参数) var newstr = Regex.Replace(str, @"[\+|\-|\*|\/]", "(*_*)"); //函数结果容器 List<decimal> list_decimal = new List<decimal>(); foreach (string hs in newstr.Split(new string[] { "(*_*)" }, StringSplitOptions.None).ToList()) { var dec = GetData(hs); list_decimal.Add(dec); } //运算符 var matches = Regex.Matches(str, @"[\+|\-|\*|\/]"); for (int de = 0; de < list_decimal.Count; de++) { if (de == 0) { result += list_decimal[de]; } else { switch (matches[de - 1].Value) { case "+": result += list_decimal[de]; break; case "-": result -= list_decimal[de]; break; case "*": result *= list_decimal[de]; break; case @"/": result /= list_decimal[de]; break; } } } } else //不带运算符 { result = GetData(str); } return result; } /// <summary> /// 数据获取 /// </summary> /// <param name="str"></param> /// <returns></returns> private decimal GetData(string str) { decimal result = 0; //解析函数 var modelFunction = GetFunction(str); switch (modelFunction.funname.ToLower()) { case "xj_je": break; case "jqy": //result = JQY(modelFunction.parameter); break; case "-jqy": //result = JQY(modelFunction.parameter); break; case "nc": result = NC(modelFunction.parameter); break; case "ye": result = YE(modelFunction.parameter); break; } return result; } #endregion /// <summary> /// 获取函数名 /// </summary> /// <param name="str">字符串</param> /// <returns></returns> private ModelFunction GetFunction(string str) { string funname = Regex.Replace(str, @"@|(\(.+\))", ""); List<string> parameter = new List<string>(); var p = Regex.Matches(str, @"\d+"); for (int i = 0; i < p.Count; i++) { parameter.Add(p[i].Value); } ModelFunction model = new ModelFunction() { funname = funname, parameter = parameter }; return model; } private class ModelFunction { /// <summary> /// 函数名称 /// </summary> public string funname { get; set; } /// <summary> /// 参数 /// </summary> public List<string> parameter { get; set; } }
分类:
C#
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现