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

本文关键字:文件 读取 数组 2d 文本 分隔 | 更新日期: 2023-09-27 18:00:28

我现在有这个:

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

我的文本文件格式如下(10行文本,每行4项用逗号分隔):

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

我不确定在for循环中的"="之后我需要什么来让它读取并将文本文件的内容拆分为2D数组。

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

我不确定在for循环中的"="之后我需要什么

上面也少了一行:

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

现在带有=的行看起来是这样的:

sQuestionAnswers[iCountLine, iCountAnswer] = tokens[iCountAnswer];

这不使用StreamReader,但它简短且易于理解:

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

行由ReadAllLines根据换行符提取。通过在每行调用Split来提取列值。它返回的锯齿状数组可以类似于多维数组使用,而且锯齿状数组通常比多维数组更快。

string line;
using (var sr = new StreamReader("answerswers.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];
            }
        }
    }
}

我建议您改变这种方法。

使用StreamReader类的ReadLine()方法浏览该文件。然后使用split(new[]{','})拆分读取行,这将为您提供每一条记录。最后,sQuestionAnswers[iCountLine,iCountAnswer]将是:仅Split数组的[iCountAnswer]的记录。