0

I have for example a line:

inputData = "-80 * 5-5"

There is the following code that splits positive numbers:

private static readonly char[] validOperators = { '/', '*', '+', '-' };

var numbersOfExpression = inputData
      .Split(validOperators, StringSplitOptions.RemoveEmptyEntries)
      .Select(s => double.Parse(s)).ToList();

But it doesn't work with negative numbers.

I am looking for a solution without Regex as it creates additional complexity.

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
ItachiU
  • 1
  • 4
  • You can't use `string.Split` for this, for the reason you've observed. If you can't use regex, you're down to parsing through your string character-by-character – canton7 Oct 25 '21 at 08:29
  • 2
    Forget Regex, you need a parser. That's a whole level more of complexity. – Enigmativity Oct 25 '21 at 08:29
  • 3
    Save your self oodles of time trying to figure order of precedence and get your self a math library capable of parsing mathematical expressions – TheGeneral Oct 25 '21 at 08:33
  • 1
    Use an available library like the `DataTable` class which [can do this out of the box](https://stackoverflow.com/questions/355062/is-there-a-string-math-evaluator-in-net/18796518#18796518): `Console.Write(new DataTable().Compute("-80 * 5-5", null));` --> -405 – Tim Schmelter Oct 25 '21 at 08:38
  • What happens with the following `-80 * 5-(-5)`? – Athanasios Kataras Oct 25 '21 at 09:48
  • @AthanasiosKataras brackets are not supported – ItachiU Oct 25 '21 at 09:53

0 Answers0