我有一个文本文件,其中包含以下内容:(没有引号和“空格”)
我希望将整个文件逐行添加到列表中:
FileStream FS = new FileStream(@"FilePath",FileMode.Open);
StreamReader SR = new StreamReader(FS);
List<string> MapLine = new List<string>();
foreach (var s in SR.ReadLine())
{
MapLine.Add(s.ToString());
}
foreach (var x in MapLine)
{
Console.Write(x);
}
我的问题出现了:我想将它添加到二维数组中。我试过了:
string[,] TwoDimentionalArray = new string[100, 100];
for (int i = 0; i < MapLine.Count; i++)
{
for (int j = 0; j < MapLine.Count; j++)
{
TwoDimentionalArray[j, i] = MapLine[j].Split('\n').ToString();
}
}
我还是C#的新手,所以请任何帮助将不胜感激。
答案 0 :(得分:0)
目前,您正在浏览文件的所有行,并且对于文件的每一行,您再次浏览文件的所有行,将它们拆分为\n
,这已经由您完成了将它们放入MapLine
。
如果你想要一个行数组的每一个字符,并且再次在一个数组中,它应该大致如下所示:
string[,] TwoDimentionalArray = new string[100, 100];
for (int i = 0; i < MapLine.Count; i++)
{
for (int j = 0; j < MapLine[i].length(); j++)
{
TwoDimentionalArray[i, j] = MapLine[i].SubString(j,j);
}
}
我没有经过测试就做到了,所以可能有问题。关键是你需要首先遍历每一行,然后遍历该行中的每个字母。从那里,您可以使用SubString
.
另外,我希望我能正确理解你的问题。
答案 1 :(得分:0)
你可以试试这个:
// File.ReadAllLines method serves exactly the purpose you need
List<string> lines = File.ReadAllLines(@"Data.txt").ToList();
// lines.Max(line => line.Length) is used to find out the length of the longest line read from the file
string[,] twoDim = new string[lines.Count, lines.Max(line => line.Length)];
for(int lineIndex = 0; lineIndex < lines.Count; lineIndex++)
for(int charIndex = 0; charIndex < lines[lineIndex].Length; charIndex++)
twoDim[lineIndex,charIndex] = lines[lineIndex][charIndex].ToString();
for (int lineIndex = 0; lineIndex < lines.Count; lineIndex++)
{
for (int charIndex = 0; charIndex < lines[lineIndex].Length; charIndex++)
Console.Write(twoDim[lineIndex, charIndex]);
Console.WriteLine();
}
Console.ReadKey();
这将把文件内容的每个字符保存到二维数组中它自己的位置。为此,char[,]
可能也被使用过。