I have a tokenization algorithm and some math expressions that do not get parsed correctly.
Here is the code:
private void GetTokens()
{
foreach (char token in test)
{
if (token.ToString().IsNumber() || token == '.' || token == ',')
{
currentToken.Append(token);
}
else if (token.IsOperator())
{
if (currentToken.Length > 0)
{
tokens.Add(currentToken.ToString());
currentToken.Clear();
}
bool minusToNegative =
tokens.Length > 0 && token == '-' &&
tokens[^1].IsOperator() && tokens[^1] != ")";
if (token == '(' && tokens[^1] == "-" && tokens[^2].IsNumber())
{
tokens[^1] = "+";
tokens.Add("-1");
tokens.Add("*");
}
if (minusToNegative)
{
currentToken.Append(token);
continue;
}
tokens.Add(token.ToString());
}
}
if (currentToken.Length > 0)
{
tokens.Add(currentToken.ToString());
}
}
I have tried to fix for one expression but then it does not work for another. There is this examples: -(((-3)-10)--12) and -23-(2+3). Parse methods for first one does not work to second and vice versa.
How can I fix it for all situations?
I would suggest a slightly different approach:
Test:
Test output: