I am a beginner in C#. I am making a web calculator like Microsoft Desktop calculator with the help of asp.net. But I'm stuck at one place. My code for Plus, minus, multiply or div is like:
protected void btnPlus_Click(object sender, EventArgs e)
{
if (txtBox1.Text.EndsWith("+"))
{
txtBox1.Text = txtBox1.Text;
}
else
{
txtBox1.Text = txtBox1.Text + "+";
ViewState["Operation"] = "+";
}
}
But I want to check this condition for all operations like minus, multiply and divide. I don't want Plus, Minus, Multiply or Div signs appear in the textbox.
You can also get the last character by using LINQ, with myString. Last() , although this is likely slower than the other answers, and it gives you a char , not a string . Save this answer.
Using String.substring() method The recommended approach is to use the substring() method provided by the String class. The idea is to take a substring from the beginning of the string and consider all the characters in it except the last n characters.
The easiest way is to use the built-in substring() method of the String class. In order to remove the last character of a given String, we have to use two parameters: 0 as the starting index, and the index of the penultimate character.
You can store all your operators in a string constant and check if the last character is contained in that string:
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"] = "+";
}
}
You can do something like the following:
Finally do the 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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With