2017-02-25 18 views
-1

所以我想問一下,如果我在一行中輸入像2 + 5這樣的輸入,所以我想將它們分成3個不同的變量,如int a = 2,b = 3,字符運算符=「+」如何在一行中輸入並分別將它們存儲在不同的變量中

PS:只是想調整我的簡單的計算器程序

+1

可以使用分割法。 –

+0

該方法是容易出錯的,而我會建議分開詢問每個部分,以便您可以輕鬆驗證輸入,如果您喜歡我的想法,我會發布有關它的答案。 –

+0

如果你只是想評估一個數學表達式[有多種方法](http://stackoverflow.com/q/333737/301857)。 –

回答

2

嘗試使用split方法

將字符串分割成基於子數組中的字符。

語法:

public string[] Split(params char[] separator) 

See more here

+0

斯普利特將刪除+? –

0

可以使用正則表達式來獲得各成分更可靠(即,此支持任何長度的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 
0

試試這個:

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] 
0

所以我要問想,如果我是把輸入像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 
} 
+0

這甚至沒有解決OP的原始問題,即如何解析輸入。這顯然需要三個不同的輸入。 – Steve

+0

如果您在他的問題中閱讀我們的聊天內容,他明確表示如果我提供替代解決方案,他會很開心....... –

+0

然後問題也應該被編輯。該頁面應該獨立運行。 – Steve

相關問題