It is required to fill a two-dimensional array with a space. Already have this code:

static void Zapolnenie(int[,] arr) { string arrs; Console.WriteLine("Введите элементы массива через пробел"); for (int i = 0; i < arr.GetLength(0); i++) { arrs = Console.ReadLine(); arrs.Split(new char[] { ' ' }); for(int j = 0; j < arr.GetLength(1); j++) arr[i, j] = int.Parse(arrs[j]); } } 

Wednesday writes that "it is not possible to convert from char to string". How to fix it?

  • arrs.Split returns result to nowhere? - gil9red pm

2 answers 2

The Split method splits a string by delimiter and returns an array that you do not save anywhere and continue to work with the original arrs string. A reference to a string by index returns a character (char) to you, while int.Parse expects a string.

It will be correct like this:

 var str = "77 88 99"; var items = str.Split(' '); var firstItem = int.Parse(items[0]); 

In your method, it will look like this:

 static void Zapolnenie(int[,] arr) { string arrs; Console.WriteLine("Введите элементы массива через пробел"); for (int i = 0; i < arr.GetLength(0); i++) { arrs = Console.ReadLine(); var items = arrs.Split(new char[] { ' ' }); for (int j = 0; j < arr.GetLength(1); j++) arr[i, j] = int.Parse(items[j]); } } 
  • but how to fix it in the context of this code? - Maxim Sorokin
  • @MaximSorokin, Updated the answer. - trydex

It is not clear why the function accepts a double array, and then fills it with numbers .. I think you need something like this (but this is not accurate):

 static int[,] Zapolnenie() { string arrs; int[,] arrayInt = new int[2,2]; Console.WriteLine("Введите элементы массива через пробел:"); for (int i = 0; i < arrayInt.GetLength(0); i++) { arrs = Console.ReadLine(); var massiv = arrs.Split(' '); //считанные данные попадают в массив for(int j = 0; j<arrayInt.GetLength(1); j++) arrayInt[i, j] = int.Parse(massiv[j]); //массив записывается в тот, который вернется } return arrayInt; } 

After that, you can call the method like this:

 var massiv = Zapolnenie();