There is such code:

int n = 6; char[,] matrix = new char[n, n]; void InsertText(char[,] matrix, string text, int n) { int temp = 0; for (int diff = 1 - n; diff <= n - 1; diff++) for (int i = 0; i < n; i++) { int j = i - diff; if (j < 0 || j >= n) continue; matrix[i, j] = text[temp]; temp++; } } void EncryptMatrix(char[,] matrix) { for (int i = 0; i < matrix.GetLength(0); i++) for (int j = 0; j < matrix.GetLength(1); j++) dataGridView1.Rows[i].Cells[j].Value = matrix[i, j]; } 

If string text = "ABCGDYWEARCHEASKLMNOPRSTUFHTSCHSHSCHYYYEYUYA"; (at the end there are three more spaces), then it writes everything correctly, but if the string is shortened, it gives an error message that goes beyond the border of the array (text). Tried to do so, they say "if temp <text.length, then matrix [i, j] = text [temp], else matrix [i, j] = '';" but I did not succeed.

enter image description here

The picture shows how it should look, if you do not remove the spaces at the end of the text variable. Please help me figure it out. I just can not understand what is wrong.

    1 answer 1

    Simply interrupt the loops with break provided если temp < text.length

    Perhaps it would be more sensible to do a common loop along the length of the line (with different arithmetic), at the beginning checking that the matrix is ​​large enough.