2013-04-25 76 views
0

我想解析包含「輸入q退出或整個數據作爲逗號分隔的字符串使用以下格式名稱,D,C,D:minQ或R:烤「來檢查用戶是否鍵入」D:「或」R:「,並根據哪一個實例化一個特定類型的對象,Decaf decafCoffee = new Decaf爲」D「:常規regCoffee = new」R: 」。最簡單的方法是什麼?解析字符串的特定值

 Console.Write("Enter q to quit or the whole data as a comma delimited string using the following format Name,D,C,D:minQ or R:roast "); 
     string s = Console.ReadLine(); 


     // Loop 
     while (!s.ToLower().Equals("q")) 
     { 
      string[] values = s.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); // Trim? 
      string name = values[0]; 
      string demand = (values[1]); 
      string cost = (values[2]); 
      string min = values[3]; 

      // Check for > 0 and convert to numbers 
      float D = CheckDemand(demand); 
      float C = CheckCost(cost); 
      float M = CheckMin(min); 

      // Create object 
      Decaf decafCoffee = new Decaf 
+0

與和'if'聲明 – OscarRyz 2013-04-25 21:25:48

+0

如何找到有價值的字符串的最後一個值中「d:」或「R」? – 2013-04-25 21:26:16

+0

格式是否改變?如果不嘗試'IndexOf'或'SubString'。 – 2013-04-25 21:27:17

回答

1
Decaf decafCoffee = null; 
Roast roastCoffee = null; 
if (min.StartsWith("D:")) 
    decafCoffee = new Decaf(); 
else if (min.StartsWith("R:")) 
    roastCoffee = new Roast(); 
else 
    // Give an error or something.