aristotaly
aristotaly

Reputation: 399

Convert string of numbers to array of numbers c#?

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?

Upvotes: 2

Views: 1673

Answers (3)

Muhammad Hasan Khan
Muhammad Hasan Khan

Reputation: 35126

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

Upvotes: 4

Ignacio Soler Garcia
Ignacio Soler Garcia

Reputation: 21855

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.

Upvotes: 1

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421978

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.

Upvotes: 1

Related Questions