【问题标题】:How do I split my text file into an 2 arrays如何将我的文本文件拆分为 2 个数组
【发布时间】:2021-09-14 06:17:24
【问题描述】:

这是我目前的代码

string filename = @"marks.txt";
try
{
    StreamReader reader = new StreamReader(filename);
    using (reader)
    {
        int lineNum = 0;
        string line = reader.ReadLine();
        while (line != null)
        {
            lineNum++;
            Console.WriteLine("{0}", line);
            line = reader.ReadLine();
        }
        Console.WriteLine(reader.ReadToEnd());
    }
}
catch (FileNotFoundException)
{
    Console.Error.WriteLine("Can not find the file {0}", filename);
}
catch (DirectoryNotFoundException)
{
    Console.Error.WriteLine("Invalid directory in file path.");
}
catch (IOException)
{
    Console.Error.WriteLine("Can not open the file {0}", filename);
}

我想要做的是它读取包含一堆标记和名称的文件,并将它们分成两个单独的数组,这样我就可以打印出谁获得了最高和最低分,平均分,还放每个人都超过了某个分数,比如 80,并为他们编写一个新文件。

编辑: 文件大致如下所示,大约有 20 行:

50 Adam
23 Jennifer
85 Sanjay

【问题讨论】:

  • 您可以通过更具体地了解“一堆标记和名称”来帮助人们。
  • 为了能够帮助您,我们需要查看文件的内容。至少是其中的一部分。或者至少是一个可行的描述。有图案吗?如果是这样,模式是什么?是用于行的分隔符吗?甚至是一行内的元素?所有这些问题你也需要问自己才能解决它
  • 如果您打算之后对生成的集合进行排序和过滤,我建议您创建一个自定义类,其中包含文件中信息(名称、标记)的属性。然后,此类的每个实例/对象可以(在拆分后)代表 1 个数据点的信息。

标签: c# arrays file


【解决方案1】:

给你:

string[] lines = File.ReadAllLines(@"file.txt");

var scores =
    lines
        .Select(x => x.Split(new[] { ' ' }, 2))
        .Select(x => new { name = x[1], score = int.Parse(x[0]) })
        .ToArray();

string highest = scores.OrderByDescending(x => x.score).Select(x => x.name).First();
string lowest = scores.OrderBy(x => x.score).Select(x => x.name).First();
double average = scores.Select(x => x.score).Average();

var over80 = scores.Where(x => x.score > 80).ToArray();
File.WriteAllLines(@"output.txt", over80.Select(x => $"{x.score} {x.name}"));

现在,如果你有两个或更多的人得分最高或最低,那么你需要这个:

string highest = String.Join(", ", scores.ToLookup(x => x.score, x => x.name)[scores.Max(x => x.score)]);
string lowest = String.Join(", ", scores.ToLookup(x => x.score, x => x.name)[scores.Min(x => x.score)]);

【讨论】:

    【解决方案2】:

    假设您的文件有这样的标记和名称:

    John Doe, 89
    David Smith, 74
    Ramkumar Sundararajan, 85
    

    在您读取行的代码中,您可以像这样拆分标记:

    string line = reader.ReadLine();
    var tokens = line.Split(',');
    string name = tokens[0];
    int marks = int.Parse(tokens[1]);
    

    如果输入格式不正确,您将需要处理错误。

    获得名称和标记后,您可以将它们存储在 Dictionary 或两个不同的数组中并对值进行操作。

    【讨论】:

    • 如果在文件中标记是第一个并且它们和名称之间有空格,这也可以吗?
    • @YeetLord05 - 如果您将文件样本添加到问题中会更好。
    • @YeetLord05,你可以把上面的代码修改成你想要的。如果要按空格分割,改:Split(' ')。如果您希望标记排在第一位,请更改:marks = int.Parse(tokens[0])。请注意,如果您的名字中有空格,那么您需要使用不同的策略。
    猜你喜欢
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多