2013-11-03 49 views
0

我有这样那样的数据在一个文本文件:从逗号提取文本分隔值在Visual Basic中

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 

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

这是我的代码:

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

你的代码有什么问题? – matzone

回答

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 
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 ...

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将包含您需要的字符串。