Reputation: 3453
So, I'm having one algorithm for parsing expressions. Also, there are conditional ways to go, whether there are brackets or not. I'm making expression and putting it in string variable, like:
string expression = "6*(3+2)";
and then I let it to go through parsing function. After it was giving me weird result, I went to debug parse function and noticed weird thing going out there: as I was iterating through characters of string from right to left with
for (int i = (expression.Length -1); i>=0; i--) ...
it didn't pass through condition
if (expression[i].Equals(")")) ...
when in expression[i] was showing on ")", because I saw it on "Locals" part in Visual Studio. Why is that? How I needed to do is:
if (expression[i].ToString() == ")") ...
and then I would be getting correct results. It didn't let me to do expression[i] == ")" because it said that I can't apply "==" operator on char and string.
So, why .Equals didn't pass when it was ")"?
Upvotes: 4
Views: 9102
Reputation: 1500385
Why is that?
Characters aren't the same as strings. A string is a sequence of characters. The type of expression[i]
is char
, not string
- so you want to compare it with a char
literal:
if (expression[i] == ')')
Note the single quotes (')'
) instead of the double quotes you were using (")"
). Single quotes are used for character literals; double quotes are used for string literals.
Upvotes: 17