2017-08-01 76 views
2

我有一個文本文件,顯示學生的名字和他們的分數。格式如下所示:如何拆分文本文件並使用整數?

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(); 
    } 
    } 
} 
+0

像以前註釋,而是用逗號分隔,而結果數組中的第二項可以嘗試一個整數。 –

回答

1

使用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()) }); 

結果: The result

我希望能對您有所幫助:)

3

首先,這是一個好主意,分離文件操作等操作。文件操作速度慢,成本高,應儘快完成。我會使用一個單獨的方法,將行讀入List並首先關閉文件操作。

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

顯然我在這裏沒有做過大量的錯誤處理,所以你應該這樣做。 – Sach

+0

通過什麼意思? – Jon

+0

正如我所示,將列表作爲參數傳遞。 – Sach