簡體   English   中英

C#。 如何將 String 轉換為 Double 數組?

[英]C#. How do i turn a String into a Double array?


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( /home/runner/distancia-entre-dois-pontos/main.cs:line 9 中的 String[] args)

任何人都可以幫忙嗎?

使用一些 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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM