2

I have a string of 9 space-separated integers, like "3 4 6 9 8 8 2 3 4", which I want to convert to a 3x3 int Array.

A simple solution is to do two loops over a new matrix and convert string values as I go. Is there a more elegant way to do this?

2
  • You might want to specify where you want the rectangular array [,] or the jagged one [][]. Commented Dec 29, 2010 at 11:43
  • i want the array to be rectangular thanks Dmitri Commented Dec 29, 2010 at 11:45

3 Answers 3

4

Using my Split extension from Split a collection into `n` parts with LINQ?

var nums = s.Split(' ').Select(n=>Int32.Parse(n)).ToList();
var grid = nums.Split(nums.Count / 3);
Sign up to request clarification or add additional context in comments.

Comments

1

Basically, your solution is as good as you can go. You can accomplish the same thing with LINQ:

int[][] result = 
    s.Split(' ')
     .Select((a, index) => new {index, value = int.Parse(a)})
     .GroupBy(tuple => tuple.index / 3)
     .Select(g => g.Select(tuple => tuple.value).ToArray())
     .ToArray();

For this problem, the LINQ solution is probably worse than the normal solution; however, the idea may be helpful for similar problems.

Comments

1

You can do an split over the " " character string.split() and you will get an array of string with the numbers. Then you must cast them to integers and distribute a plain array to you desired array and as far as I know there is no way to do that in another way that iterating through the array, but you will need only 1 loop.

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.