1

So i am attempting to make a calculator and I am unsure of how to take the equation and split it up into operators and operands. I have chosen to do this by using the string.split function to turn it into an array of numbers and operators to which i can then compare and output the result. However I want to throw and error if the user enters " + 100" as it will expect a operand first. This is my code to check the above condition

String equation = txt_equation.Text;
String[] equationArray= new String [30];
equationArray = equation.Split(' ');

if (equationArray[0] == "+" || equationArray[0] == "-" || equationArray[0] == "/" || equationArray[0] == "*")
{
   System.Windows.Forms.MessageBox.Show("The equation entered is incorrect");
}
else
{...}

The problem is when I enter "100 + 100" it does get split up as:

equationArray[0] = "100"
equationArray[1] = "+"
equationArray[2] = "100"

but if I enter " + 100" the result is:

equationArray[0] = ""
equationArray[1] = "+"
equationArray[2] = "100"

Side note users enter in the numbers / operands with buttons numbers are entered into the equation as "n" operands as " operator " allowing the spaces to break it up

Artiom
  • 7,694
  • 3
  • 38
  • 45
C. Dodds
  • 325
  • 3
  • 12
  • 1
    _String.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries)_ The " + 100" contains an initial space that produces an empty element in the destination array. By the way, you don't need to initialize the destination array – Steve Oct 07 '16 at 09:29
  • That worked thanks :) – C. Dodds Oct 07 '16 at 09:31
  • More info at https://stackoverflow.com/questions/6111298/best-way-to-specify-whitespace-in-a-string-split-operation?rq=1 (look at the second best answer) – Steve Oct 07 '16 at 09:34

3 Answers3

1

There is a space before +, so it will split there with an empty string on one side and + on the other.

You might find the option to remove empty entries useful - this would also result in collapsing multiple spaces between tokens.

StringSplitOptions.RemoveEmptyEntries to omit empty array elements from the array returned; or StringSplitOptions.None to include empty array elements in the array returned.

equation.Split(new []{' '}, StringSplitOptions.RemoveEmptyEntries);
Charles Mager
  • 25,735
  • 2
  • 35
  • 45
0

I would also assume "1 + 2" is legal, i.e. in general whitespace of any length is only of relevance for splitting tokens ? Therefore you need to use an overload of Split that takes a StringSplitOptions https://msdn.microsoft.com/en-us/library/system.stringsplitoptions(v=vs.110).aspx and specify RemoveEmptyEntries

tolanj
  • 3,651
  • 16
  • 30
-1

if you wanted the application to check if it is a legit whole number, you could just add equationArray[0] == null || equationArray[0] == "" || equationArray[0] == " " to your if statement.

DerpyDog
  • 37
  • 7