C# text file to 2d array?
If I create a 2d array like so:
int[,] MyArray = new int开发者_如何学C[5, 5];
and have a text file with these numbers:
1 2 3 4 5
5 4 3 2 1
1 2 3 4 5
2 3 4 6 7
7 8 9 6 4
How do I get the numbers into the 2d array?
This should be fairly straightforward. Nested loops are the "traditional" way to handle multidimensional arrays.
Nest two loops, the outer iterating over lines in the input, the inner over numbers in a line.
string[] line = text.split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < line.Length; i++)
{
string[] digit = text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
for (int j = 0; j < digit.Length; j++)
{
MyArray[i, j] = Convert.ToInt32(digit[j]);
}
}
However you want...
Basically you have to decide.
Here is a heuristic:
- Read in the file
- Parse the numbers
- Calculate the sizes of the arrays
- Insert the numbers in the appropriate locations.
精彩评论