将文本文件拆分为2D数组

时间:2016-06-30 13:54:44

标签: c# visual-studio multidimensional-array file-io

这是我要分割成2D数组的文本文件

"YHOO",36.86,21,13873900,37.00 "GOOG",684.11,1114,1821650,686.72 "MSFT",50.54,3993,31910300,50.65 "AAPL",94.40,28201,39817000,94.26

这是我为实现此目的而实施的代码,但它不会起作用

 String input = File.ReadAllText(@"..\..\Data\stockInfo.txt");

        int i = 0, j = 0;
        string[,] result = new string[3, 5];
        foreach (var row in input.Split('\n'))
        {
            j = 0;
            foreach (var col in row.Trim().Split(','))
            {
                result[i, j] = string.Parse(col.Trim());
                j++;
            }
            i++;
        }

2 个答案:

答案 0 :(得分:1)

Jagged数组String[][](数组数组)通常比2D String[,]更灵活:

  string[][] result = File
    .ReadLines(@"..\..\Data\stockInfo.txt")
    .Select(line => line.Split(','))
    .ToArray();

如果您坚持 2D阵列,则必须放置效率较低的代码

  string[] lines = File.ReadAllLines(@"..\..\Data\stockInfo.txt");

  string[,] result = null;

  for (int i = 0; i < lines.Count; ++i) { 
    string[] items = lines.Split(',');

    if (null == result)
      result = new string[lines.Count, items.Length];

    for (int j = 0; j < items.Length; ++j) 
      result[i, j] = items[j];
  }

答案 1 :(得分:0)

数组的大小错误。此外,您不需要string.Parse,因为Split的输出是IEnumerable of strings

int i = 0, j = 0;
string[,] result = new string[4, 5];
foreach (var row in input.Split('\n'))
{
    j = 0;
    foreach (var col in row.Trim().Split(','))
    {
        result[i, j] = col.Trim();
        j++;
    }
    i++;
}