2010-07-01 57 views
1

提取它們的處理我有以下的文本文件(ExamMarks.txt)如何閱讀字符串和整數的分隔行和VB

約翰,85,95,90

邁克爾,60,75,75

我想提取一條線,取的名字,並分別與單獨的整數。然後,我想打印的名稱和編號的標籤一般是這樣的:

約翰的平均值是90

邁克爾的平均值是70

到目前爲止,我只能顯示什麼是在文本文件中的標籤(見下文):

Dim FILE_NAME As String = "C:\ExamMarks.txt" 
Dim TextLine As String 

If System.IO.File.Exists(FILE_NAME) = True Then 

    Dim objReader As New System.IO.StreamReader(FILE_NAME) 

    Do While objReader.Peek() <> -1 
    TextLine = TextLine & objReader.ReadLine & vbNewLine 

    Loop 

    lblResults.Text = TextLine 

Else 

    MsgBox("File Does Not Exist") 

End If 

任何幫助表示讚賞。

+0

肯定有代碼VB.Net,而不是VB6!我編輯了這個問題並相應地重新簽名。 – MarkJ 2010-07-01 19:26:14

回答

1

對文件中的每一行執行此處理。它假定名稱始終是字符串中的第一個單詞,然後計算字符串中所有數字的平均值。

'Split the test string on commas 
Dim strScores() As String = strTest.Split(",".ToCharArray) 
Dim strWord As String 
Dim intTotalScore As Integer 
Dim intCountOfScores As Integer 
Dim intAverageScore As Integer 

'Name is the first word in the line 
strName = strScores(1).Trim 

For Each strWord In strScores 
    If IsNumeric(strWord) Then 
     intTotalScore = intTotalScore + Int(strWord.Trim) 
     intCountOfScores = intCountOfScores + 1 
    End If 
Next 

'Calculate the average  
intAverageScore = intTotalScore/intCountOfScores 
0

你可以做到這一切更簡單一些更現代的代碼:

  1. 使用內置TextFieldParser讀取逗號分隔的文件,並訪問每一行作爲一個字符串數組。它比使用Split更簡單,更強大。
  2. 然後使用IEnumerableextension methods來計算一行中的全部平均值。
    a。 Skip(1)跳過第一個條目。 b。 Average()可讓您將剩餘的條目轉換爲Double,然後取平均值。

像這樣:

Sub Main()  
    Using MyReader As New _ 
     Microsoft.VisualBasic.FileIO.TextFieldParser("ExamMarks.txt") 
     MyReader.TextFieldType = FileIO.FieldType.Delimited 
     MyReader.SetDelimiters(",") 

     Dim currentRow As String() 
     While Not MyReader.EndOfData 
     Try 
      ' Read row as an array of strings ' 
      currentRow = MyReader.ReadFields() 
      ' Calculate average ' 
      Dim dAverage As Double = _ 
      currentRow.Skip(1).Average(Function(s) Convert.ToDouble(s)) 
      ' Write out result ' 
      Console.WriteLine(currentRow(0) & "'s average is " & _ 
      Convert.ToString(dAverage)) 
     Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException 
      MsgBox("Line " & ex.Message & "is not valid and will be skipped.") 
     End Try 
     End While 
    End Using 
    Console.ReadLine() 
    End Sub 
相關問題