Saif Elkholy
Saif Elkholy

Reputation: 37

Splitting text file into 2D array

this is the text file that i want to split into a 2D array

"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

and this is the code I have implemented to do this but it won't work

 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++;
        }

Upvotes: 0

Views: 2071

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186833

Jagged array String[][] (array of array) is often more flexible than 2D one String[,]:

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

If you insist on 2D array you have to put less efficient code

  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];
  }

Upvotes: 1

paczek
paczek

Reputation: 46

The size of array was wrong. Also, you don't need to string.Parse, as output of Split is 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++;
}

Upvotes: 0

Related Questions