简体   繁体   中英

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);

The final part of it isn't working, for some reason. After i enter the imput, the console says

Unhandled exception. System.FormatException: Input string was not in a correct format. at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type) at System.Double.Parse(String s) at System.Array.ConvertAll[TInput,TOutput](TInput[] array, Converter`2 converter) at Program.Main(String[] args) in /home/runner/distancia-entre-dois-pontos/main.cs:line 9

Can anyone help?

Use some LINQ and Extension methods

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM