C# Read from text file separated by commas into 2d

2019-08-05 07:59发布

I currently have this:

using (StreamReader sr = new StreamReader("answers.txt"))
{
    for (iCountLine = 0; iCountLine < 10; iCountLine++)
    {
         for (iCountAnswer = 0; iCountAnswer < 4; iCountAnswer++)
         {
             sQuestionAnswers[iCountLine, iCountAnswer] = 
         }
    }
}

My text file is formatted like this (10 lines of text, with 4 items on each line separated by commas):

example, example, example, example 
123, 123, 123, 123

I'm not sure what I need after the "=" in the for loop to get it to read and split the contents of the text file into the 2D array.

4条回答
虎瘦雄心在
2楼-- · 2019-08-05 08:23

I'd suggest you to change the approach.

Go over the file using ReadLine() method of a StreamReader class. Then split the read line using Split(new[]{','}), and this will give you every single record. And finally the sQuestionAnswers[iCountLine, iCountAnswer] will be: the just Split array's [iCountAnswer]'s record.

查看更多
姐就是有狂的资本
3楼-- · 2019-08-05 08:26

I'm not sure what I need after the "=" in the for loop

There's also a line missing above it:

var tokens = sr.ReadLine().Split(',');

Now the line with = would look like this:

sQuestionAnswers[iCountLine, iCountAnswer] = tokens[iCountAnswer];
查看更多
Summer. ? 凉城
4楼-- · 2019-08-05 08:26
string line;

using (var sr = new StreamReader("answers.txt"))
{
    while ((line = sr.ReadLine()) != null)
    {
        for (int iCountLine = 0; iCountLine < 10; iCountLine++)
        {
            var answers = line.Split(',');
            for (int iCountAnswer = 0; iCountAnswer < 4; iCountAnswer++)
            {
                sQuestionAnswers[iCountLine, iCountAnswer] = answers[iCountAnswer];
            }
        }
    }
}
查看更多
来,给爷笑一个
5楼-- · 2019-08-05 08:32

This doesn't use StreamReader, but it's short and easy to understand:

        string[] lines = File.ReadAllLines(@"Data.txt");
        string[][] jaggedArray = lines.Select(line => line.Split(',').ToArray()).ToArray();

Rows are extracted by ReadAllLines according to newline. Columns values are extracted by calling Split on every line. It returns jagged array that you can use similarly to multidimensional array, also jagged arrays are generally faster than multidimensional arrays.

查看更多
登录 后发表回答