gpt4 book ai didi

c# - 如何拆分文本文件并使用整数?

转载 作者:行者123 更新时间:2023-11-30 20:30:00 25 4
gpt4 key购买 nike

我有一个显示学生姓名和分数的文本文件。格式如下所示:

James Johnson, 85
Robert Jones, 90
Lindsey Parks, 98
etc.

我有 10 个名字和分数都采用上述格式。我的问题是如何通过分隔符拆分文本文件,并使用文本文件中的整数

到目前为止,这是我的代码:

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.FileIO;
namespace TextFiles1
{
class Program
{
static void Main(string[] args)
{
StreamReader sr = new StreamReader(@"C:\Users\jonda\Desktop\StudentScores.txt.txt");
string data = sr.ReadLine();
while (data != null)
{
Console.WriteLine(data);
string[] names = data.Split(',');
data = sr.ReadLine();
}
int total = 0;
double average = 0;
for (int index = 0; index < data.Length; index++)
{
total = total + data[index];
}
average = (double)total / data.Length;
Console.WriteLine("Average = " + average.ToString("N2"));
int high = data[0];
for (int index = 0; index < data.Length; index++)
{
if (data[index] > high)
{
high = data[index];
}
}

Console.WriteLine("Highest Score =" + high);
sr.Close();
Console.ReadLine();
}
}
}

最佳答案

首先,最好将文件操作和其他操作分开。文件操作速度慢且成本高,应尽快完成。我会使用单独的方法,将行读入列表并先关闭文件操作。

    private static List<string> ReadFile(string path)
{
List<string> records = new List<string>();
using (StreamReader sr = new StreamReader(path))
{
while (!sr.EndOfStream)
records.Add(sr.ReadLine());
}
return records;
}

然后我将该列表传递给另一个函数并计算平均值、最大值等。

private static void CalculateAverage(List<string> lines)
{
char[] seperator = new char[] { ',' };
List<int> scores = new List<int>();
if (lines != null && lines.Count > 0)
{
foreach (string line in lines)
{
Console.WriteLine(line);
string[] parts = line.Split(seperator);
int val;
if (int.TryParse(parts[1], out val))
scores.Add(val);
}
}
Console.WriteLine("Average: {0}", scores.Average());
Console.WriteLine("Highest Score: {0}", scores.Max());
}

然后在你的主程序中调用这样的方法:

List<string> lines = ReadFile(path);
CalculateAverage(lines);

关于c# - 如何拆分文本文件并使用整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45444186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com