简体   繁体   中英

How to convert string to 2D array of double?

I have this variable:

string coord = "[[1,2,3,4], [5,6,7,8], ...]";

And at the end I expect to be:

double[][] d = [[1,2,3,4], [5,6,7,8], ...]

Here is the code that I already tried:

double[] d = coord.Split(",").Select(n => Convert.ToDouble(n)).ToArray();

It gives me an error: System.FormatException: 'Input string was not in a correct format.' My question:

  1. How to resolve the above error?

  2. Is there any proper ways to do that conversion, if anyone has the pseudo-code to solve this conversion it really helps me a lot.

Update:

Here is the pseudo-code that comes in my mind:

//convert string to one-dimensional array of double
//grap every 4 elements to be put on a single array
//add a single array that consist of 4 elements to the 2-dimensional array of double.
//Verify the result

Your string seems to be in JSON Format (A quick google search will tell you what this is, if you are not familiar with it)

Why dont you just use System.Text.Json or Newtonsoft.JSON (second needs to be installed via NuGet)?

The code would then look as follows:

string input = "[[1,2,3,4], [12,1,52,3], [1,4,2,3]]";
double[][] output = System.Text.Json.JsonSerializer.Deserialize<double[][]>(input);

You can try this.

What it does is

//convert string to string[] with elements like "1,2,3,4", "5,6,7,8"
//convert each "1,2,3,4" in the array to string[] { "1", "2", "3", "4" }
    // Now we have string[][] = { { "1","2","3","4" }, { "5","6","7","8" } }
//convert each string[] to double[] by applying Double.Parse

var d = Array.ConvertAll<string[], double[]>
(
    coord.Replace(" ", "").Replace("],[", "|").Replace("[", "").Replace("]", "").Split('|')
    .Select(n => n.Split(','))
    .ToArray(),
    n => Array.ConvertAll(n, Double.Parse)
);

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