解析特定值的字符串

时间:2013-04-25 21:23:28

标签: c# string parsing split

我试图解析包含“输入q以退出或整个数据作为逗号分隔的字符串使用以下格式名称,D,C,D:minQ或R:roast”的字符串来检查用户是否键入“D:”或“R:”并且根据哪一个,实例化特定类型的对象,Decaf decafCoffee =新的Decaf为“D”:和常规regCoffee = new Regular为“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

1 个答案:

答案 0 :(得分: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.