-1

I have gone through this solution. But this is not solving my problem. Let's say I have a string:

var aString = "0 -1 12 456 -512";

I want to convert this string to an int array like:

var convertedArray = [0, -1, 12, 456, -512];

How should I approach to solve this problem?

Mauro Bilotti
  • 5,628
  • 4
  • 44
  • 65
Shunjid Rahman
  • 409
  • 5
  • 17
  • 9
    `aString.Split(' ').Select(s => int.Parse(s)).ToArray();` – René Vogt Oct 31 '19 at 12:39
  • This is a duplicate of [Split string, convert ToList() in one line](https://stackoverflow.com/questions/911717/split-string-convert-tolistint-in-one-line) – aloisdg Oct 31 '19 at 13:30

2 Answers2

1
var convertedArray = Array.ConvertAll(aString.Split(' '), int.Parse);
Tasos K.
  • 7,979
  • 7
  • 39
  • 63
Marwen Jaffel
  • 703
  • 1
  • 6
  • 14
1

You can simply do this:

var stringNumbers = aString.Split(' ');
var numbers = new int[stringNumbers.Length];
for (int i = 0; i < stringNumbers.Length; i++)
    numbers[i] = Convert.ToInt32(stringNumbers[i]);