从txt文件创建二维数组

本文关键字:二维数组 文件创建 txt | 更新日期: 2023-09-27 18:27:38

好吧,我已经读到了一个.txt文件。。。现在我正试图找出将这些信息转换为2D阵列的最佳方法。

我的文本文件(前两个数字提供高度和宽度):

5
5
0,0,0,0,0
0,0,0,0,0
0,0,1,0,0
0,1,1,1,0
1,1,1,1,1

我的C#/XNA:

string fileContents = string.Empty;
try
{
    using (StreamReader reader = new StreamReader("Content/map.txt"))
    {
        fileContents = reader.ReadToEnd().ToString();
    }
}
catch (Exception e)
{
    Console.WriteLine(e.Message);
}

现在我接下来需要做的是定义二维映射数组的大小,然后填充条目值。。。这就是我有点陷入困境的地方,我已经找到了各种方法来循环处理数据,但我认为其中任何一种都不太整洁。

我试着做的是用换行符分隔一个循环。。。然后是用逗号分隔符分隔的另一个循环。

这是最好的方法吗…还是有更好的选择?

从txt文件创建二维数组

它可以用LINQ完成,但只有当您想要(接受)一个数组int[][]而不是一个直的二维int[,]时,这才是实用的。

int[][] data = 
    File.ReadLines(fileName)
    .Skip(2)
    .Select(l => l.Split(',').Select(n => int.Parse(n)).ToArray())
    .ToArray();

下面的代码不需要样本中的第一行到第二行。CSV文件:

5
5

我更喜欢这种方式,但因此,下面的代码会读取该文件两次。这将需要一个小的修改,使用示例中的前两行。

private int[,] LoadData(string inputFilePath)
{
  int[,] data = null;
  if (File.Exists(inputFilePath))
  {
    Dictionary<string, int> counts = GetRowAndColumnCounts(inputFilePath);
    int rowCount = counts["row_count"];
    int columnCount = counts["column_count"];
    data = new int[rowCount, columnCount];
    using (StreamReader sr = File.OpenText(inputFilePath))
    {
      string s = "";
      string[] split = null;
      for (int i = 0; (s = sr.ReadLine()) != null; i++)
      {
        split = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        for (int j = 0; j < columnCount; j++)
        {
          data[i, j] = int.Parse(split[j]);
        }
      }
    }
  }
  else
  {
    throw new FileDoesNotExistException("Input file does not exist");
  }
  return data;
}
private Dictionary<string, int> GetRowAndColumnCounts(string inputFilePath)
{
  int rowCount = 0;
  int columnCount = 0;
  if (File.Exists(inputFilePath))
  {
    using (StreamReader sr = File.OpenText(inputFilePath))
    {
      string[] split = null;
      int lineCount = 0;
      for (string s = sr.ReadLine(); s != null; s = sr.ReadLine())
      {
        split = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        if (columnCount == 0)
        {
          columnCount = split.Length;
        }
        lineCount++;
      }
      rowCount = lineCount;
    }
    if (rowCount == 0 || columnCount == 0)
    {
      throw new FileEmptyException("No input data");
    }
  }
  else
  {
    throw new FileDoesNotExistException("Input file does not exist");
  }
  Dictionary<string, int> counts = new Dictionary<string, int>();
  counts.Add("row_count", rowCount);
  counts.Add("column_count", columnCount);
  return counts;
}

这是我提出的似乎有效的解决方案。

int[,] txtmap;
int height = 0;
int width = 0;
string fileContents = string.Empty;
try
{
    using (StreamReader reader = new StreamReader("Content/map.txt"))
    {
        fileContents = reader.ReadToEnd().ToString();
    }
}
catch (Exception e)
{
    Console.WriteLine(e.Message);
}
string[] parts = fileContents.Split(new string[] { "'r'n" }, StringSplitOptions.None);
for (int i = 0; i < parts.Length; i++)
{
    if (i == 0)
    {
        // set width
        width = Int16.Parse(parts[i]);
    }
    else if (i == 1)
    {
        // set height
        height = Int16.Parse(parts[i]);
        txtmap = new int[width, height];
    }
    if (i > 1)
    {
        // loop through tiles and assign them as needed
        string[] tiles = parts[i].Split(new string[] { "," }, StringSplitOptions.None);
        for (int j = 0; j < tiles.Length; j++)
        {
            txtmap[i - 2, j] = Int16.Parse(tiles[j]);
        }
    }
}