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;
}
}
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];
}
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With