2 回答

TA贡献1820条经验 获得超3个赞
在我看来,您事先并不知道文件的行数,并且在拆分行时也不知道项目的数量。在这种情况下,我不会使用固定矩阵,而是使用字典等。
static void Main(string[] args)
{
Dictionary<int, string[]> filesData = new Dictionary<int, string[]>();
importFiles(filesData);
}
static void importFiles(Dictionary<int, string[]> filesData)
{
var path = @"export/file.txt";
if (File.Exists(path))
{
string[] fileLines = File.ReadAllLines(path);
for (int i = 0; i < fileLines.Length; i++)
{
string line = fileLines[i];
string[] split = line.Split(';');
for (int j = 0; j < split.Length; j++)
{
split[j] = split[j].Trim();
}
int index = filesData.Count == 0 ? 0: filesData.Keys.Max();
filesData.Add(index + 1, split);
}
}
}

TA贡献1865条经验 获得超7个赞
如果矩阵中的行数与读取的行数不同(例如抛出异常),您可以在代码中处理情况:
static void importFiles(string[,] matrix)
{
var path = @"export/file.txt";
if (!File.Exists(path)) return;
string[] fileLines = File.ReadAllLines(path);
if(fileLines.Length != matrix.GetLength(0))
// here you have couple of opitions
// throw new ArgumentException("Number of rows in passed matrix is different from number of lines in a file!");
// or just do nothing:
return;
string[,] map = new string[fileLines.Length, fileLines[0].Split(';').Length];
for (int i = start; i < fileLines.Length; i++)
{
string line = fileLines[i];
for (int j = 0; j < matrix.GetLength(1); j++)
{
string[] split = line.Split(';');
matrix[i, j] = split[j]?.Trim();
}
}
}
或者你可以matrix在你的方法中初始化你的数组:
string[] fileLines = File.ReadAllLines(path);
// c is number of columns, that you are using now
string[,] matrix = new string[fileLines.Length, c];
- 2 回答
- 0 关注
- 167 浏览
添加回答
举报