2010-07-01 58 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 
相关问题