【问题标题】:C#. How do i turn a String into a Double array?C#。如何将 String 转换为 Double 数组?
【发布时间】:2022-01-17 07:08:49
【问题描述】:

class Program {
 public static void Main (string[] args) {
   
 string S1 = Console.ReadLine();
 string S2 = Console.ReadLine();

 double [] D1 = Array.ConvertAll(S1.Split(' '), Double.Parse);
 double [] D2 = Array.ConvertAll(S2.Split(' '), Double.Parse);

由于某种原因,它的最后一部分不起作用。我输入输入后,控制台说

未处理的异常。 System.FormatException:输入字符串的格式不正确。 在 System.Number.ThrowOverflowOrFormatException(ParsingStatus 状态,TypeCode 类型) 在 System.Double.Parse(String s) 在 System.Array.ConvertAll[TInput,TOutput](TInput[] 数组,Converter`2 转换器) 在 Program.Main(String[] args) 在 /home/runner/distancia-entre-dois-pontos/main.cs:line 9

谁能帮忙?

【问题讨论】:

  • 您的代码看起来正确,但它不能处理虚假输入。如果您输入“123 abc”,Double.Parse 将在尝试解析“abc”时抛出 FormatException。如何解决这个问题取决于您想要的行为。

标签: c# arrays double


【解决方案1】:

使用一些 LINQ 和扩展方法

static class Program
{
    static void Main(string[] args)
    {
        string text1 = "4376.0 4328.0 14.71 116.7 14.01 0.9912 46.74";
        double[] row1 = text1.ParseList();
        string text2 = "4376.0,4328.0,14.71,116.7,14.01,0.9912,46.74";
        double[] row2 = text2.ParseList(',');
    }
}

public static class Extensions
{
    public static double[] ParseList(this string text, char token = ' ')
    {
        return text.Split(token).Select((item) => ParseValue(item)).ToArray();
    }
    public static double ParseValue(this string text)
    {
        if (double.TryParse(text.Trim(), out double x))
        {
            return x;
        }
        return 0;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多