使用'x'
字符作爲運算符,什麼函數會輸入一個可以包含數字或兩個數字相乘的字符串?使用'x'運算符計算數字乘積的函數?
例如:
- 如果輸入是
"6 x 11"
則輸出應該是66
。 。 - 如果輸入
"78
「,那麼輸出應該是78
使用'x'
字符作爲運算符,什麼函數會輸入一個可以包含數字或兩個數字相乘的字符串?使用'x'運算符計算數字乘積的函數?
例如:
"6 x 11"
則輸出應該是66
。 。"78
「,那麼輸出應該是78
嗯,你可以使用幾種System.String的方法來完成這個你嘗試過什麼
一個選項:?
public int GetValue(string input)
{
int output = 0;
if (input.Contains("x"))
{
string[] a = input.Split('x');
int x = int.Parse(a[0]);
int y = int.Parse(a[1]);
output = x * y;
}
else
{
output = int.Parse(input);
}
return output;
}
當然,這忽略任何輸入驗證。
選中此
public int GetProduct(string input)
{
int result = 1;
input = input.ToUpper();
if (input.Contains("X"))
{
string[] array = input.Split('x');
for (int index = 0; index < array.Length; index++)
{
if (IsNumber(array[index]))
{
result = result * Convert.ToInt32(array[index]);
}
}
}
else
{
result = Convert.ToInt32(input);
}
return result;
}
bool IsNumber(string text)
{
Regex regex = new Regex(@"^[-+]?[0-9]*\.?[0-9]+$");
return regex.IsMatch(text);
}
:你的問題解決了嗎? – Sumeshk