简体   繁体   English

C#从用逗号分隔的文本文件读入2d数组

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

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): 我的文本文件格式如下(10行文本,每行4个项目用逗号分隔):

 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. 我不确定在for循环中的“=”后我需要什么来让它读取并将文本文件的内容拆分成2D数组。

I'm not sure what I need after the "=" in the for loop 在for循环中的“=”之后我不确定我需要什么

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

This doesn't use StreamReader , but it's short and easy to understand: 这不使用StreamReader ,但它简短易懂:

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

Rows are extracted by ReadAllLines according to newline. 根据换行符由ReadAllLines提取行。 Columns values are extracted by calling Split on every line. 通过在每一行上调用Split来提取列值。 It returns jagged array that you can use similarly to multidimensional array, also jagged arrays are generally faster than multidimensional arrays. 它返回可以类似于多维数组使用的锯齿状数组,锯齿状数组通常比多维数组更快。

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

I'd suggest you to change the approach. 我建议你改变方法。

Go over the file using ReadLine() method of a StreamReader class. 使用StreamReader类的ReadLine()方法遍历文件。 Then split the read line using Split(new[]{','}), and this will give you every single record. 然后使用Split(new [] {','})拆分读取行,这将为您提供每条记录。 And finally the sQuestionAnswers[iCountLine, iCountAnswer] will be: the just Split array's [iCountAnswer]'s record. 最后,sQuestionAnswers [iCountLine,iCountAnswer]将是:刚刚拆分数组的[iCountAnswer]的记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM