例如,我有一个程序可以计算中间有空格的 1 + 1,但是如何在我的代码中使其也可以计算没有空格的 1 + 1?我正在考虑正则表达式或分割字符串,但我无法成功!
有人可以帮我吗?
这是我的代码:
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;
// rekent percentage van een bedrag
case '%':
answer = (a / b * 100).ToString();
break;
default:
throw new InvalidOperationException();
}
// Show the answer
ShowNotification(clipboardText, answer);
}
提前致谢!
偶然的你
月关宝盒
紫衣仙女
相关分类