How can I convert a string of numbers separated by a space into an array of int with one line of code?

I divided it into strings, but I don’t know how to convert it into an int array without creating an additional string array.

int [] Mas = textBox1.Text.Split(' ') 
  • 2
    and one line of code is the principle condition? - torokhkun
  • And why do you need an array? Awfully awkward data structure. - VladD

4 answers 4

Try the following

 int[] a = textBox1.Text.Split(' ').Select(x => int.Parse(x)).ToArray(); 

It would be more correct to write

 int[] a = textBox1.Text.Split(' '). Where(x => !string.IsNullOrWhiteSpace( x )). Select(x => int.Parse(x)).ToArray(); 
  • 2
    The answer below is no Where is more interesting ru.stackoverflow.com/a/451169/177411 - ad1Dima
  • And all this can be wrapped in an extension method, and then the code will be even less written. - ad1Dima
  • @ ad1Dima: Well, any function can be wrapped in an extension. var result = source.ExtensionConverSourceToResult(); - VladD

Since such a codegolf has gone ...

short version without LINQ, if you do not need to cut spaces:

 Array.ConvertAll(text.Split(),int.Parse); 

a slightly longer option for the case when you need to cut spaces:

 Array.ConvertAll(Regex.Split(text,@"\s+"),int.Parse); 

Minimal options via LINQ without / c RemoveEmptyEntries

 text.Split().Select(int.Parse).ToArray(); text.Split(new[]{' '},StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray(); 
  • +1, but I’m not sure if it’s better with a regular schedule (faster, more readable) than with LINQ. - VladD
  • The @VladD regular replaces Linq, not Split(new[]{' '},StringSplitOptions.RemoveEmptyEntries) . I can add a variant without cutting out spaces and without regular work :) - PashaPash
  • And really! I shouldn’t make categorical statements after 11 pm :) - VladD
  • one
    By the way, did not know about Array.ConvertAll . (But I don’t have a second plus.) - VladD
  • @VladD I didn’t know either , googled on enSO half an hour ago)) - PashaPash
 int[] result = textBox1.Text.Split( new[]{" "}, StringSplitOptions.RemoveEmptyEntries ).Select(x => int.Parse(x)).ToArray(); 
     int[] a = textBox1.Text.Split(' ').Select(int.Parse).ToArray();