[英]from text file into 2D array
我不知道如何制作功能程序,我想將文本文件傳輸到二維數組中。
謝謝你的回答
這是我的文本文件的內容:
0000000011
0011100000
0000001110
1000011100
1000000000
0000111111
1000001100
1000000000
1000011000
1000001111
代碼:
static void Main(string[] args)
{
int[,] map = new int[10, 10];
StreamReader reader = new StreamReader(@"Lode.txt");
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
**WHAT I SHOULD PUT HERE**
}
}
reader.Close();
}
您應該執行以下操作(帶有我的評論的代碼):
var map = new int[10, 10];
using (var reader = new StreamReader("Lode.txt")) // using will call close automatically
{
for (var i = 0; i < 10; i++)
{
var line = reader.ReadLine(); // read one line from file
for (var j = 0; j < 10; j++)
{
map[i, j] = Int32.Parse(line[j].ToString()); // get one symbol from current line and convert it to int
}
}
}
您可以嘗試使用一點 LINQ,如下所示:
static void Main(string[] args)
{
string filePath = @"Lode.txt";
// Read file contents and store it into a local variable
string fileContents = File.ReadAllText(filePath);
/* Split by CR-LF in a windows system,
then convert it into a list of chars
and then finally do a int.Parse on them
*/
int[][] map = fileContents.Split('\r', '\n')
.Select(x => x.ToList())
.Select(x => x.Select(y => int.Parse(new string(y, 1))).ToArray())
.ToArray();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.