2013-04-25 80 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.