Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# write chars to 2-dimensional array more efficiently

Tags:

c#

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;
    }
}
like image 717
Mantas Lukosevicius Avatar asked Jul 19 '26 05:07

Mantas Lukosevicius


2 Answers

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];
    }
}
like image 93
Rok Povsic Avatar answered Jul 20 '26 18:07

Rok Povsic


You might use ToCharArray method and only one loop:

char [][] array = new char[6][];
for (int i = 0; i < 6; i++)
{
    array[i] = text.Substring(i * 20, 20).ToCharArray();
}
like image 31
Konstantin Ivanov Avatar answered Jul 20 '26 19:07

Konstantin Ivanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!