如何有效地解析字符串?

时间:2019-04-13 13:48:22

标签: c#

我需要解析以下字符串。我需要解析5.5数据。我正在使用进行解析。解析左侧表示英尺,右侧表示英寸值。

 if ((height.Contains("."))) I'm using this code parse the value.but we gave only.5 it throws an exception. how to handle it efficient way?
 int feet = Convert.ToInt16((height.Split('.')[0]));
 int inch = Convert.ToInt16((height.Split('.')[1]));

2 个答案:

答案 0 :(得分:0)

好的,正如注释中提到的,这表明了为什么您应该进行检查,以便捕获未使用正确格式的字符串,并且可以返回错误。

以下是使用基本方法来捕获字符串可能会变形的几种基本方法。

string height = "3.4";

if(height.Contains("."))
{
    string[] parts = height.Split(".");
    if(parts.Length == 2)
    {
        int feet;
        int inchs;

        if (int.TryParse(parts[0], out feet) && int.TryParse(parts[1], out inchs))
        {
            Console.WriteLine(feet + " Feet and " + inchs + " Inchs");
        }
        else
        {
            Console.WriteLine("Unable to convert string to feet and inch integers");
        }
    }
    else
    {
        Console.WriteLine("Incorrect string format, too many decimal marks (" + parts.Length + ")");
    }

}
else
{
    Console.WriteLine(height + " Feet and 0 Inchs");
}

以此为例,说明如何检查尝试执行的异常。

答案 1 :(得分:0)

“ 5。4”之类的输入有效吗?负值呢?

您可能会喜欢以下方法:

private void button1_Click(object sender, EventArgs e)
{
    string input = ".5";
    Tuple<int, int> height;
    if (TryParseHeight(input, out height))
    {
        Console.WriteLine("Feet: " + height.Item1.ToString());
        Console.WriteLine("Inches: " + height.Item2.ToString());
    }
    else
    {
        Console.WriteLine("Failed.");
    }
}

private bool TryParseHeight(string strInput, out Tuple<int, int> Foot_Inches)
{
    int feet, inches;
    Foot_Inches = new Tuple<int, int>(-1, -1); // assume failure until proven otherwise
    string[] values = strInput.Trim().Split(".".ToCharArray());
    switch(values.Length)
    {
        case 1: // no "." was present, attempt to parse only feet and assume 0 (zero) inches
            if (int.TryParse(values[0], out feet))
            {
                if (feet >= 0)
                {
                    Foot_Inches = new Tuple<int, int>(feet, 0); // success!
                    return true;
                }
                else
                {
                    return false; // negative feet?!
                }                        
            }
            else
            {
                return false; // invalid feet
            }

        case 2: // exactly one "." was present, attempt to parse both feet and inches
            values[0] = values[0].Trim();
            values[1] = values[1].Trim();
            if (values[0].Length == 0 && values[1].Length == 0)
            {
                return false; // both feet and inches were missing
            }
            else
            {
                // at least one side was not blank...
                // ...fill in the missing side with a zero
                values[0] = values[0].Length == 0 ? "0" : values[0];
                values[1] = values[1].Length == 0 ? "0" : values[1];

                if (int.TryParse(values[0], out feet) && int.TryParse(values[1], out inches))
                {
                    if(feet >= 0 && inches >= 0)
                    {
                        Foot_Inches = new Tuple<int, int>(feet, inches); // success!
                        return true;
                    }
                    else
                    {
                        return false; // one of the sides, feet or inches, was negative?!
                    }
                }
                else
                {
                    return false; // one of the sides, feet or inches, was invalid
                }
            }


        default: // more than one "." was present!
            return false;

    }         
}