所以我想問一下,如果我在一行中輸入像2 + 5這樣的輸入,所以我想將它們分成3個不同的變量,如int a = 2,b = 3,字符運算符=「+」如何在一行中輸入並分別將它們存儲在不同的變量中
PS:只是想調整我的簡單的計算器程序
所以我想問一下,如果我在一行中輸入像2 + 5這樣的輸入,所以我想將它們分成3個不同的變量,如int a = 2,b = 3,字符運算符=「+」如何在一行中輸入並分別將它們存儲在不同的變量中
PS:只是想調整我的簡單的計算器程序
斯普利特將刪除+? –
可以使用正則表達式來獲得各成分更可靠(即,此支持任何長度的INT編號):
class Program
{
static void Main(string[] args)
{
var input = "20+5";
var regex = new Regex(@"(\d+)(.)(\d+)");
if (regex.IsMatch(input))
{
var match = regex.Match(input);
var a = match.Groups[1].Value;
var op = match.Groups[2].Value;
var b = match.Groups[3].Value;
Console.WriteLine($"a: {a}");
Console.WriteLine($"operator: {op}");
Console.WriteLine($"b: {b}");
}
}
}
輸出
a: 20
operator: +
b: 5
試試這個:
string strResult = Console.ReadLine();
//On here, we are splitting your result if user type one line both numbers with "+" symbol. After splitting,
// we are converting them to integer then storing the result to array of integer.
int[] intArray = strResult.Split('+').Select(x => int.Parse(x)).ToArray();
現在,您現在可以通過其索引來訪問你的號碼
intArray[0]
//or
intArray[1]
所以我要問想,如果我是把輸入像2+ 5 in one line所以我想分開他們在3個不同的變量,如int a = 2, b = 3和char operator ='+'
您可以使用params數組將任意數量的參數傳遞給方法,然後您可以將它們分開。
實施例:
public int Result(params char[] input){
// split the input
// any necessary parsing/converting etc.
// do some calculation
// return the value
}
可以使用分割法。 –
該方法是容易出錯的,而我會建議分開詢問每個部分,以便您可以輕鬆驗證輸入,如果您喜歡我的想法,我會發布有關它的答案。 –
如果你只是想評估一個數學表達式[有多種方法](http://stackoverflow.com/q/333737/301857)。 –