Mantas Lukosevicius Mantas Lukosevicius - 27 days ago 5
C# Question

C# write chars to 2-dimensional array more efficiently

I have a text string of 120 characters. I want to make 2-dimensional char array, 6 lines with 20 characters. I wonder if i could do this more efficiently, using less variables? Thanks.

Loop:

int i = 0, u = 0;

for (int x = 0; x < 120; x++)
{
array[i, u] = text[x];

u++;

if (u == 19)
{
i++;
u = 0;
}
}

Answer

You might do it like this:

int numRows = 6;
int numCols = 20;
for (int rowIdx = 0; rowIdx < numRows; rowIdx++)
{
    for (int colIdx = 0; colIdx < numCols; colIdx++)
    {
        array[rowIdx, colIdx] = text[rowIdx * numCols + colIdx];
    }
}