簡體   English   中英

如何拆分文本文件並使用整數?

[英]How can I split a text File and use the Integers?

我有一個文本文件,顯示學生的姓名和分數。 格式如下:

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

使用Regex查找每個人的信息,然后拆分每個人並提取NameScore

嘗試這樣:

        var inputStr = "James Johnson, 85 Robert Jones, 90 Lindsey Parks, 98";
        var regex = new Regex(@"[A-z]* [A-z]*, [0-9]*");
        return  regex.Matches(inputStr)
            .OfType<Match>()
           .Select(p => p.Value.Split(','))
           .Select(p => new { Name = p[0], Score = Convert.ToInt32(p[1].Trim()) });

結果: 結果

希望對您有所幫助:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM