简体   繁体   中英

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?

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

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.

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.

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