c# - 在计算器应用程序中将运算符从减号更改为加号,反之亦然
问题描述
这是我关于计算器的第一个问题,请耐心等待。我必须做一个按钮来反转加减运算符。所以 1+2-3 会变成 1-2+3。我使用 btnChangeOperator 将一个简单的字符串(如 1+2)管理为 1-2,反之亦然。但是,当我尝试 1+2-3 并想将其更改为 1-2+3 时,我得到了 1+2+3,然后是 1-2-3。我首先尝试使用正则表达式:
Regex pattern = new Regex("[+-]");
if (txtInput1.Text.Contains("-"))
{
txtInput1.Text = pattern.Replace(txtInput1.Text, "--");//jace can manage that, I also tried "+"
txtInput2.Text = pattern.Replace(txtInput2.Text, "+");
}
else if (txtInput1.Text.Contains("+"))
{
txtInput1.Text = pattern.Replace(txtInput1.Text, "+-");//jace can manage that, I also tried with "-"
txtInput2.Text = pattern.Replace(txtInput2.Text, "-");
}
这仅适用于 1+2 或 1-2 和 1+2+3 或 1-2-3,但不适用于 1+2-3 或 1-2+3。我也尝试过替换,但这是同样的问题:
if (txtInput1.Text.Contains("-"))
{
txtInput1.Text = txtInput1.Text.Replace("-", "+");
txtInput2.Text = txtInput2.Text.Replace("-", "+");
}
else if (txtInput1.Text.Contains("+"))
{
txtInput1.Text = txtInput1.Text.Replace("+", "-");
txtInput2.Text = txtInput2.Text.Replace("+", "-");
}
我还尝试先将其更改为数学算术,例如 +-/-+=- 和 --=+,然后再将其更改为 +/-。但这不起作用,因为 +- 会变成 +。我使用Jace 加法来计算,这非常好。我也想过一个开关盒,但我没有设法实现它。有人能指出我正确的方向吗,因为困难在于加号可以是减号,但在我的代码中它会再次直接变为加号。谢谢你。
编辑:我使用了 Joe Phillips 的答案,它非常简单和好,没有 if 语句,只有 1 行代码(好吧 2,因为我有 2 个 txtFields)。
txtInput1.Text = txtInput1.Text.Replace("+", "p").Replace("-", "+").Replace("p", "-");
txtInput2.Text = txtInput2.Text.Replace("+", "p").Replace("-", "+").Replace("p", "-");
谢谢大家。
解决方案
如果您只是将减号更改为加号,反之亦然,请使用正则表达式替换匹配评估器
var text = "001-34+323";
Regex.Replace(text, "[-+]", me => { return me.Value == "-" ? "+" : "-"; })
结果
001+34-323
如果需要,您可以让匹配评估器考虑更多场景,只需在大括号之间添加更多代码。
推荐阅读
- javascript - 需要计算gridview.after databind VB.NET的高度
- android - 折叠工具栏在夜间模式下改变颜色
- c++ - C ++中数组中的整数元素重复多少次
- python - 如何在 CPLEX python 中编写条件约束?
- python - 使用 BeautifulSoup 搜索特定的 div
- reverse-engineering - 使用 Ghidra 脚本从 PE 获取导入/导出
- go - 无法返回任何 k8s client-go 对象
- sql-server - 使用 SQL Server 中的动态列名称从临时表更新表
- python - 与特定组中python上一行的差异百分比
- java - 创建实现类存在一些差异的工厂的最佳实践