vb.net读取文本文件,拆分为随机范围

时间:2014-12-30 14:44:48

标签: .net vb.net

我想将List的文本行读入2到5行的随机范围并保存到链接。

例如:我有test.txt文件,其中包含以下内容:

aa
bb
cc
dd
ee
ff
gg
hh
ii
yy
tt
rr
ee
ww
qq
uu
oo
pp

这段代码:

Dim random As New Random()
Dim n As Integer
n = random.Next(2, 5)
Dim textfile As String = "test.txt"
Dim objReader As New System.IO.StreamReader(textfile)
Dim List As String = objReader.ReadToEnd()
Do While Not EOF()
Dim link As List(Of String) = TextLink(resp)
Loop

因此,如果我运行它将读取aa,bb并保存到'链接'字符串列表和连续它将随机读取下一行,如cc,dd,ee,ff并保存到' link'。

这就是我想要做的。

1 个答案:

答案 0 :(得分:1)

这是一个简单的例子:

    Dim R As New Random
    Dim Count As Integer
    Dim RangeLength As Integer
    Dim DataFileName As String = System.IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "test.txt")
    Dim Links As New List(Of List(Of String))
    Using SR As New System.IO.StreamReader(DataFileName)
        While Not SR.EndOfStream
            Count = 0
            RangeLength = R.Next(2, 6)
            Dim curLinkSet As New List(Of String)
            Links.Add(curLinkSet)
            While Not SR.EndOfStream AndAlso Count < RangeLength
                curLinkSet.Add(SR.ReadLine)
                Count = Count + 1
            End While
        End While
    End Using

    For i As Integer = 0 To Links.Count - 1
        Debug.Print("Set #" & i)
        Dim LinkSet As List(Of String) = Links(i)
        For x As Integer = 0 To LinkSet.Count - 1
            Debug.Print(x & ": " & LinkSet(x))
        Next
        Debug.Print("")
    Next

示例输出:

Set #0
0: aa
1: bb
2: cc

Set #1
0: dd
1: ee
2: ff
3: gg
4: hh

Set #2
0: ii
1: yy
2: tt
3: rr

Set #3
0: ee
1: ww
2: qq
3: uu

Set #4
0: oo
1: pp