C# 从文本文件到二维数组
我不知道如何制作函数程序,我想把文本文件转换成二维数组 谢谢你的回答 这是我的文本文件的内容:C# 从文本文件到二维数组,c#,arrays,C#,Arrays,我不知道如何制作函数程序,我想把文本文件转换成二维数组 谢谢你的回答 这是我的文本文件的内容: 0000000011 0011100000 0000001110 1000011100 1000000000 0000111111 1000001100 1000000000 1000011000 1000001111 代码: static void Main(字符串[]args) { int[,]map=新的int[10,10]; StreamReader=新的StreamReader(@“Lod
0000000011
0011100000
0000001110
1000011100
1000000000
0000111111
1000001100
1000000000
1000011000
1000001111
代码:
static void Main(字符串[]args)
{
int[,]map=新的int[10,10];
StreamReader=新的StreamReader(@“Lode.txt”);
对于(int i=0;i<10;i++)
{
对于(int j=0;j<10;j++)
{
**我应该在这里放什么**
}
}
reader.Close();
}
您应该执行以下操作(用我的注释编写代码):
var-map=newint[10,10];
using(var reader=newstreamreader(“Lode.txt”)//using将自动调用close
{
对于(变量i=0;i<10;i++)
{
var line=reader.ReadLine();//从文件中读取一行
对于(var j=0;j<10;j++)
{
map[i,j]=Int32.Parse(行[j].ToString());//从当前行获取一个符号并将其转换为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();
}
我的控制台应用程序在此代码之后是空的。我不知道为什么你什么意思?在初始化之后,您是否尝试将
map
打印到控制台?嗯,也许我很笨,但我不知道如何…我对(var I=0;I<10;I++){for(var j=0;j<10;j++){console.Write(map[I,j]);}console.WriteLine()非常熟悉谢谢你的帮助……我想知道我是否可以把这个“游戏板”藏起来,然后在点击后它们会单独出现。
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
}
}
}
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();
}