I make a program in which you can calculate an amount. And get a result out of it now that it works when I run operator 1 + 1, but not without spaces like 1 + 1. Now I want it to work in both cases. Can anyone help me with this? Since I don't know if that is also possible in my code.
I thought of removing all the spaces in my string and then splitting each character. So first replace (replace) all spaces in your string with string.Empty and then you split on an empty character.
Maybe someone can help me out?
This is my code
private char[] SPACE = new char[] { ' ' };
private void GetAnswer(string clipboardText)
{
//Loop through all questions and answers
foreach (question q in questionList)
{
//If we have found an answer that is exactly the same show an Notification
//Startwith zoekt naar alle vragen die matchen vanaf het begin van de zin en Endwith alle vragen die matchen vanaf het eind van de zin//
if (q._question.StartsWith(clipboardText) || q._question.EndsWith(clipboardText))
{
ShowNotification(q._question, q._answer);
break;
}
}
var parts = clipboardText.Split(SPACE);
var isValid = true;
Double a, b;
// Make sure it's format A # B
if (parts.Length != 3)
return;
// Parse first number
isValid = Double.TryParse(parts[0], out a);
if (!isValid)
return;
var validOperators = new char[] { '+', '-', ':', 'x' };
// Parse operator
if (parts[1].Length != 1)
return;
var op = parts[1][0];
if (!validOperators.Contains(op))
return;
// Parse 2nd number
isValid = Double.TryParse(parts[2], out b);
if (!isValid)
return;
// Now calculate the answer
string answer = null;
switch (op)
{
case '+':
answer = (a + b).ToString();
break;
case '-':
answer = (a - b).ToString();
break;
case ':':
if (b == 0)
answer = "NaN";
else
answer = (a / b).ToString();
break;
case 'x':
answer = (a * b).ToString();
break;
default:
throw new InvalidOperationException();
}
// Show the answer
ShowNotification(clipboardText, answer);
}