这是我的文件功能,它从文件中获取数据并将其放入数组中:
public void populate_grid_by_file()
{
String store_data_from_file = string.Empty;
try
{
using (StreamReader reader = new StreamReader("data.txt"))
{
store_data_from_file = reader.ReadToEnd().ToString();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
string[] line = store_data_from_file.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < line.Length; i++)
{
string[] alphabet = store_data_from_file.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
for (int j = 0; j < alphabet.Length; j++)
{
Sodoku_Gri[i, j] = alphabet[j];
}
}
}
以下是文件中写的内容:
1--2--3-- 3-4-4-5-- -7-3-4--- 7--5--3-6 --7---4-- 3-2--4-5- ------3-- 2-6--7--- 4---4--3-
这就是我想要打印的内容:
1 - - 2 - - 3 - - 3 - 4 - 4 - 5 - - - 7 - 3 - 4 - - - 7 - - 5 - - 3 - 6 - - 7 - - - 4 - - 3 - 2 - - 4 - 5 - - - - - - - 3 - - 2 - 6 - - 7 - - - 4 - - - 4 - - 3 -
我想过这样做:
public void display_grid()
{
for (int row = 0; row < Sodoku_Gri.GetLength(0); row++)
{
for (int col = 0; col < Sodoku_Gri.GetLength(1); col++)
{
Console.Write(Sodoku_Gri[row, col]);
Console.Write(" ");
}
Console.WriteLine();
}
}
我只是无法理解为什么2d阵列在最后一行打印了9次额外的------------!
它应该是一个二维数组,每个元素之间有间距,就像我在文件中显示数据但是没有间距。
答案 0 :(得分:1)
您正在将数据拆分为行,看起来您在内部循环中的意图是处理当前行中的字符。但是,实际上,您正在为每个行迭代处理整个文件,这就是为什么您的输出包含所有文件的字符*行数。请改为尝试此调整:
public void populate_grid_by_file()
{
String store_data_from_file = string.Empty;
try
{
using (StreamReader reader = new StreamReader("data.txt"))
{
store_data_from_file = reader.ReadToEnd().ToString();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
string[] line = store_data_from_file.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < line.Length; i++)
{
//string[] alphabet = store_data_from_file.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
string[] alphabet = line[i].Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries)
for (int j = 0; j < alphabet.Length; j++)
{
Sodoku_Gri[i, j] = alphabet[j];
}
}
}