clear last entry in calculator using C#
I have a string;
string str = "3+4*2+8";
This string is entered by user开发者_如何学Go.. I want to do an operation in which I just want to remove last entry of string. i.e 8 in this particular example..... Please guide me how to do this....
If all you're talking about are simple arithmetic expressions with positive integers, then you can probably use
Regex.Replace(str, @"([+*/-]|[0-9]+)$", "")
Testing:
PS Home:\> '3+4*2+8' -replace '([+*/-]|[0-9]+)$'
3+4*2+
PS Home:\> '3+4*2+' -replace '([+*/-]|[0-9]+)$'
3+4*2
PS Home:\> '1-42' -replace '([+*/-]|[0-9]+)$'
1-
you can always find the last non digit char in the input and remove all the other chars from there so basically :
- validate input...
- get last non digit char index
- return the string removing anything from that index
here is a very simple example
public static string TrimLastEntry(string text)
{
// input is valid ?, check any additional rules of your own....
if (string.IsNullOrEmpty(text))
{
return text;
}
// get last index of a non digit char
int idx = text.Length - 1;
for (; idx > 0; --idx)
{
if (!char.IsDigit(text[idx]))
{
break;
}
}
// replace the last
return text.Remove(idx + 1);
}
this for sure will need more validation on the allowed inputs and their structure but should give you a starting point
- it could be only me but i have a little issue with variable that are named like common type names, IntelliSense completions gets annoying :)
To remove the "last" entry, you need to define what the last entry is.
For instance, what is that "last" entry for 3*(1+2)
Is is 2
, or (1+2)
, or *(1+2)
?
Are you going to have text in these expressions:
"Hello" + " " + "world!"
would be easy, but
"This is an expression: " + "1 + \"a\""
might be a bit more difficult to handle with regular expressions.
Back in the day, before XML, we had a tool that let you create lexical scanners so that you could create languages and then analyze or manipulate them. Check out Flex.
As usual, wikipedia has good entry on Lexical Analysis.
精彩评论