如何将文本文件逐行转换为 Visual Basic 2008 中的数组?

How to convert a text file to an array in Visual Basic 2008 line by line?

我刚接触 Visual Basic,正在尝试阅读文件。从我在网上找到的内容来看,我还没有发现任何不完全让我感到困惑的东西。

我正在尝试制作一个简单的游戏来测试一些对话内容,我希望可以预先确定您可以说的选项。现在我在数组中有几个句子,但我真正想做的只是将所有内容键入一个文本文件,每行有一个不同的项目,然后将每一行转换为数组的一个单独项目。

我现在拥有的是:

Dim convoStarters() As String = {"Hello", "Who are you?", "Who the hell are you?"}

我想做的是从这样组织的文本文件中获取信息:

Hello
Who are you?
Who the hell are you?

并将每一行放入一个数组中,该数组看起来与我上面的数组完全一样(当然,除了我会向文本文件中添加更多内容)。

谢谢你帮助一个新人,祝你有愉快的一天。

首先你要弄清楚,你的数组需要多少个元素。

通过计算 '","' + 1 的数量,您可以得到字符串中存在的元素数量。

请查看字符串方法,如 instr()、mid()、left()、rtrim()、ltrim() ..

根据您找到的元素数量,您可以 REDIM 数组,或 REDIM PRESERVER 数组

对于您的示例 REDIM strArr(nrElements) 或者如果您需要添加一些元素而不 丢失内容使用 REDIM PRESERVE strArr(nrElements).

然后就可以填写了: 对于 x = LBound(strArr,1) 到 Ubound(strArr,1) strArr(x) = 字符串部分(x) 下一个 x

始终在菜单 "view" 下的 VBA 编辑器中打开 "direct window" 并使用 debupg.print strArr(x)

假设你的意思是 VB.NET 而不是 VBA(既是为了 Visual Studio 的标签,也是为了开发游戏),你可以使用 StreamReader逐行读取文件并将元素添加到字符串中,然后:

VB.NET 解决方案

注意:如果您还没有这样做,要与任何文件(输入或输出)交互,您需要导入系统的 IO,这意味着在您的代码之上声明:

Imports System.IO

...然后...

全局变量(在模块顶部,在任何 sub/function 之外)

Dim myStringElements As Integer
Dim convoStarters() As String

子代码 Public 订阅 yourSub() 我的字符串元素 = 0 Dim sr As StreamReader = New StreamReader(path) '这个对象将读取文本文件

Do While sr.Peek() >= 0 'this will loop through the lines until the end
    AddElementToStringArray(sr.ReadLine()) 'this will add the single line to the string array
Loop
sr.Close()
End Sub

PUBLIC FUNCTION BODY(完成添加工作的另一个子)

Public Sub AddElementToStringArray(ByVal stringToAdd As String)
    ReDim Preserve convoStarters(myStringElements)
    convoStarters(myStringElements) = stringToAdd
    myStringElements += 1
End Sub

VBA 解决方案

但是,如果在您的评论中您的意思是 VBA,那么逻辑是相同的,但语法略有不同:

全局变量

Dim myStringElements As Integer
Dim convoStarters() As String

子代码

    myStringElements = 0
    Open "C:\Users\Matteo\Desktop\Test.txt" For Input As #1

    While Not EOF(1)
        Line Input #1, DataLine ' read in data 1 line at a time
        AddElementToStringArray (DataLine) 'this will add the single line to the string array
    Wend

PUBLIC 函数体

Public Sub AddElementToStringArray(ByVal stringToAdd As String)
    ReDim Preserve convoStarters(myStringElements)
    convoStarters(myStringElements) = stringToAdd
    myStringElements += 1
End Sub