我有一个程序可以读取文本文件中的单词。我的代码完美无缺,但为什么它只读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个单词中的单词:
任何人都可以帮我解决问题吗?
答案 0 :(得分:-1)
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
函数,因此它需要FileStart
和FileEnd
作为参数。这使得使用更加动态。如果你不想/只需要它删除它们并将它们添加为您之前的局部变量)。
修改:wordCount
变量的明确字符串声明
Eidt2 :由于.NET 3.5而添加了ToArray()