如何读取分隔的字符串和整数行并提取它们以便在VB中处理

时间:2010-07-01 17:20:56

标签: vb.net text file-io csv label

我有以下文本文件(ExamMarks.txt)

John,85,95,90

Micheal,60,75,75

我想提取一行并分别取名和单独和整数。然后我想在标签中打印名称和数字的平均值:

约翰的平均值为90

Micheal的平均值为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

感谢任何帮助。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您可以使用更现代的代码更简单地完成所有这些:

  1. 使用内置TextFieldParser读取逗号分隔文件,并以字符串数组的形式访问每一行。它比使用Split更简单,更健壮。
  2. 然后使用IEnumerable extension methods计算一行中的平均值 一个。 Skip(1)跳过第一个条目 湾Average()允许您将剩余的条目转换为Double,然后取平均值。
  3. 像这样:

      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