本文介绍了读取文件拆分并添加到字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好.我试图读取一个文本文件,其内容如下:

你好:再见,cu,再见
以后:很晚,很晚,很晚

等.

我想逐行阅读此文档,在:"字符上拆分每一行.然后将第一个值存储为字典中的键,然后将第二个存储为值.

这是我的代码:

hello. I was trying to read a text file which has content like this :

hello:bye,cu,goodbye
later:late,very late, ver very late

etc. etc.

I want to read this document line by line, split each line on ":" char. Then store first value as a key in dictionary and second as value.

this is my code:

Dim sr As StreamReader = New StreamReader(sFileName)
        sInputLine = sr.ReadLine()
        Do Until sInputLine Is Nothing
            sInputLine = sr.ReadLine()
            If (sInputLine <> "") Then
                Dim sites As String() = Nothing
                sites = sInputLine.Split(":")
                Dim a, b As New ArrayList
                a.Add(sites(0))
                b.Add(sites(1))
                If (sync.syndict.ContainsKey(a.ToString)) Then
                    sync.syndict.Item(a.ToString) = sync.syndict.Item(a.ToString) + "," + b.ToString
                Else
                    sync.syndict.Add(a.ToString, b.ToString)
                End If
            End If
        Loop
        sr.Close()




但它不起作用.有什么建议?

另外当我使用tring数组代替arraylist这样的时候




but its not working. Any suggestions?

Also when i use a tring array in place of arraylist like this

Dim sites2(2) As String
sites2 = sr.ReadLine.Split(":")
            sync.syndict.Add(sites2(0), sites2(1))



它显示了一个错误:对象未初始化,在第一行上(拆分集)



it shows an error : object not initialized, on first line (split staetment)

推荐答案

<br />
<pre>Dim sFileName As String = "C:\test.txt"<br />
       Dim syndict As New Dictionary(Of String, String)<br />
       Dim sr As StreamReader = New StreamReader(sFileName)<br />
       Dim sInputLine As String = sr.ReadLine()<br />
       Do Until sInputLine Is Nothing<br />
           If (sInputLine <> "") Then<br />
               Dim sites As String() = Nothing<br />
               sites = sInputLine.Split(":")<br />
               If (syndict.ContainsKey(sites(0))) Then<br />
                   syndict.Item(sites(0)) = syndict.Item(sites(0)) + "," + sites(1)<br />
               Else<br />
                   syndict.Add(sites(0), sites(1))<br />
               End If<br />
           End If<br />
           sInputLine = sr.ReadLine()<br />
       Loop<br />
       sr.Close()<br />
   End Sub</pre><br />
<br />



请告知这是否可以解决您的问题.
否则,指定该对象未初始化异常的确切显示位置.

如有必要,您可以添加对拆分的字符串数组(站点)的检查,然后再通过索引访问它,或者捕获该异常.
还要确保每一行只有一个'':'',否则您可能会得到意想不到的结果.



Kindly let know if this is solving your issue.
Or else specify where exactly this object not initialized exception is shown.

If necessary you can add check for the splitted string array(sites) before accessing it by index or catch exception for that.
Also make sure that each line has only one '':''.Otherwise you may get unexpected results.


这篇关于读取文件拆分并添加到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 19:22