从Visual Basic中的逗号分隔值中提取文本

时间:2013-11-03 02:12:22

标签: vb.net

我在文本文件中有这样的数据:

12343,M,Helen Beyer,92149999,21,F,10,F,F,T,T,T,F,F
54326,F,Donna Noble,92148888,19,M,99,T,F,T,F,T,F,T
99999,M,Ed Harrison,92147777,28,F,5,F,F,F,F,F,F,T
88886,F,Amy Pond,92146666,31,M,2,T,F,T,T,T,T,T
37378,F,Martha Jones,92144444,30,M,5,T,F,F,F,T,T,T
22444,M,Tom Scully,92145555,42,F,6,T,T,T,T,T,T,T
81184,F,Sarah Jane Smith,92143333,22,F,5,F,F,F,T,T,T,F
97539,M,Angus Harley,92142222,22,M,9,F,T,F,T,T,T,T
24686,F,Rose Tyler,92142222,22,M,5,F,F,F,T,T,T,F
11113,F,Jo Grant,92142222,22,M,5,F,F,F,T,T,T,F

我想提取名字的首字母和完整的姓氏。所以输出应该如下:

H. Beyer, M
D. Noble, F
E. Harrison, M

问题是我不应该使用String Split功能。相反,我必须使用任何其他字符串处理方式。

这是我的代码:

Public Sub btn_IniSurGen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_IniSurGen.Click
    Dim vFileName As String = "C:\temp\members.txt"
    Dim vText As String = String.Empty

    If Not File.Exists(vFileName) Then
        lbl_Output.Text = "The file " & vFileName & " does not exist"
    Else
        Dim rvSR As New IO.StreamReader(vFileName)
        Do While rvSR.Peek <> -1
            vText = rvSR.ReadLine() & vbNewLine
            lbl_Output.Text += vText.Substring(8, 1)
        Loop
        rvSR.Close()
    End If

End Sub

3 个答案:

答案 0 :(得分:1)

您可以使用TextFieldParserClass。它将解析文件并将结果作为字符串数组直接返回给您。

Using MyReader As New Microsoft.VisualBasic.FileIO.
    TextFieldParser("c:\logs\bigfile")

    MyReader.TextFieldType = 
        Microsoft.VisualBasic.FileIO.FieldType.Delimited
    MyReader.Delimiters = New String() {","}
    Dim currentRow As String()
    'Loop through all of the fields in the file.  
    'If any lines are corrupt, report an error and continue parsing.  
    While Not MyReader.EndOfData
        Try
            currentRow = MyReader.ReadFields()
            ' Include code here to handle the row. 
        Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
            MsgBox("Line " & ex.Message & 
            " is invalid.  Skipping")
        End Try 
    End While 
End Using

答案 1 :(得分:0)

对于您想要的结果,您可以更改

lbl_Output.Text += vText.Substring(8, 1)

'declare this first
Dim sInit as String
Dim sName as String


sInit = vText.Substring(6, 1)
sName = ""
For x as Integer = 8 to vText.Length - 1
  if vText.Substring(x) = "," Then Exit For
  sName &= vText.Substring(x)
Next

lbl_Output.Text += sName & ", " & sInit

但更好的是你有多个lbl_Output ......

答案 2 :(得分:0)

这样的事情应该有效:

    Dim lines As New List(Of String)
    For Each s As String In File.ReadAllLines("textfile3.txt")
        Dim temp As String = ""
        s = s.Substring(s.IndexOf(","c) + 1)
        temp = ", " + s.First
        s = s.Substring(s.IndexOf(","c) + 1)
        temp = s.First + ". " + s.Substring(s.IndexOf(" "c), s.IndexOf(","c) - s.IndexOf(" "c)) + temp
        lines.Add(temp)
    Next

列表Lines将包含您需要的字符串。