从文本文件创建2D数组

时间:2012-03-12 20:38:15

标签: c# string multidimensional-array xna xna-4.0

好的,所以我设法读取.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);
}

现在我需要做的是定义二维地图数组的大小然后填充条目值...这是我有点卡住的地方,并找到了我可以循环的各种方法数据,但我认为它们中的任何一个都不是非常整洁。

我试图做的是有一个循环按换行分割...然后是另一个用逗号分隔符分割的循环。

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

3 个答案:

答案 0 :(得分:5)

可以使用LINQ完成,但只有当您想要(接受)数组数组int[][]而不是直接的2维int[,]时才能实现。

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

答案 1 :(得分:0)

下面的代码不需要示例.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;
}

答案 2 :(得分:0)

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

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]);
        }
    }
}
相关问题