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

妖精的绣舞 提交于 2019-12-11 12:55:25

问题


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.


回答1:


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



回答2:


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.




回答3:


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



回答4:


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.



来源:https://stackoverflow.com/questions/15025468/c-sharp-read-from-text-file-separated-by-commas-into-2d-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!