C# 如何查找文本框文本的最后一个字符?
我是C#的初学者。在asp.net的帮助下,我正在制作一个类似Microsoft桌面计算器的web计算器。但我被困在一个地方。我的加、减、乘或除法代码如下:C# 如何查找文本框文本的最后一个字符?,c#,asp.net,C#,Asp.net,我是C#的初学者。在asp.net的帮助下,我正在制作一个类似Microsoft桌面计算器的web计算器。但我被困在一个地方。我的加、减、乘或除法代码如下: protected void btnPlus_Click(object sender, EventArgs e) { if (txtBox1.Text.EndsWith("+")) { txtBox1.Text = txtBox1.Text; } else { txtB
protected void btnPlus_Click(object sender, EventArgs e)
{
if (txtBox1.Text.EndsWith("+"))
{
txtBox1.Text = txtBox1.Text;
}
else
{
txtBox1.Text = txtBox1.Text + "+";
ViewState["Operation"] = "+";
}
}
但我想检查所有运算的这个条件,比如减法,乘法和除法。我不希望加号、减号、乘号或除号出现在文本框中。您可以执行以下操作:
if (txtBox1.Text != "")
{
char last_char = txtBox1.Text[txtBox1.Text.Length - 1];
switch (last_char)
{
case '+':
ViewState["Operation"] = "+";
txtBox1.Text.Remove(txtBox1.Text.Length - 1);
break;
case '-':
ViewState["Operation"] = "-";
txtBox1.Text.Remove(txtBox1.Text.Length - 1);
break;
// do the same for all operators
default:
break;
}
}
您可以将所有运算符存储在字符串常量中,并检查最后一个字符是否包含在该字符串中:
private const string OPERATORS = "+-/*";
protected void btnPlus_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtBox1.Text) || // check if string is empty
OPERATORS.Contains(txtBox1.Text.Last())) // or if last character is a operator
{
txtBox1.Text = txtBox1.Text;
}
else
{
txtBox1.Text = txtBox1.Text + "+";
ViewState["Operation"] = "+";
}
}
txtBox1.Text[txtBox1.Text.Length-1]
?