从文本文件中读取单词

时间:2016-11-25 09:33:13

标签: vb.net

我有一个程序可以读取文本文件中的单词。我的代码完美无缺,但为什么它只读1个字?

代码:

Public Function ReadFile1() As String
    Dim text = IO.File.ReadAllText("APStringFile\file.txt")
    ' Counting words
    Dim words = text.Split(" "c)
    Dim wordCount As String
    Dim Hasil As String
    Dim FileStart As Integer = 0
    Dim FileEnd As Integer = 100

    For i As Integer = FileStart To FileEnd
        wordCount = words(i)
        'Hasil = wordCount(i)
    Next i
    Return wordCount
End Function

我想读取0到100之间的单词。但结果只能读取100个单词中的单词:

enter image description here

任何人都可以帮我解决问题吗?

1 个答案:

答案 0 :(得分:-1)

您可以使用LINQ SkipTake

简化代码
Public Function ReadFile1(FileStart As Integer, FileEnd As Integer) As String
    Dim text = IO.File.ReadAllText("APStringFile\file.txt")

    ' Counting words
    Dim words = text.Split(" "c)

    'Skip the first n words then take m words
    'where n = FileStart (e.g. 0) and m = delta between FileEnd (e.g. 100) and FileStart.
    'Concat the result together to one string 
     Dim wordCount As String = String.Join(" ", words.Skip(FileStart).Take(FileEnd - FileStart).ToArray())

    Return wordCount
End Function

使用示例:

Console.WriteLine(ReadFile1(0, 100)) 'Prints words 0 to 100
Console.WriteLine("---------")
Console.WriteLine(ReadFile1(101, 200)) 'Prints words 101 to 200

(我调整了ReadFile1函数,因此它需要FileStartFileEnd作为参数。这使得使用更加动态。如果你不想/只需要它删除它们并将它们添加为您之前的局部变量)。

修改wordCount变量的明确字符串声明
Eidt2 :由于.NET 3.5而添加了ToArray()