1

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
3
  • 1
    You can't split on the commas because you have commas delineating both the sub-arrays and their individual elements. You need to figure out a way to split out the sub arrays first and then split out the elements. One possible solution involves a regex, but I'm sure there's much better ways . Commented Apr 9, 2020 at 11:33
  • You could try removing ("trim") leading and trailing "[" and "]" and then split by "], [". Then you have an array of strings like "1,2,3,4" and "5,6,7,8". Now you can split each of those by "," and convert the individual elements to double. Commented Apr 9, 2020 at 11:38
  • Why not use JSON.NET to deserialize to an (anonymous e.g.) class? Commented Apr 9, 2020 at 11:48

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Straight to the point. I deleted my overly complex answer. This should be the accepted answer.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.