【问题标题】:Displaying each element of array on new line在新行上显示数组的每个元素
【发布时间】:2014-10-19 12:02:18
【问题描述】:

在尝试阅读和回答我的问题时,请考虑我是 VB.NET 的新手

我有一个文本框,其中包含在同一行上用逗号分隔的单词列表。单击按钮时,字符串被分配给变量文本,然后我将其拆分为变量arrayText。 然后我循环它并在新行上显示数组的每个元素。

我的代码如下所示

 Dim text As String
 Dim arrayText() As String

    text = TextBox1.Text
    arrayText = text.Split(",") 'every "," generates new array index, removes ","

    text = ""

    For i = 0 To arrayText.Length Step 1
        text = arrayText(i) & vbCrLf
        MsgBox(text)
    Next

调试时我得到错误消息数组越界,但是当我删除换行符 (vbCrLf) 时,它会在消息框(我用于调试)和循环结束时逐字显示我的文本它以相同的错误消息退出。

我在这里做错了什么,有什么改进建议吗?

【问题讨论】:

    标签: vb.net


    【解决方案1】:

    虽然 walther 的回答是正确的,但我建议您使用 List(Of String)For Each...Next 循环。

    列表更“现代”,大多数时候它比 vb.net 中的数组更受欢迎。您可以使用Environment.NewLine 代替vbCrLf。我不确定你到底想做什么,但我不认为使用MsgBox 是呈现分隔词的最佳方式。这是我认为您应该做的一个简单示例:

    ' Hold the text from the text box.
    Dim FullText As String = TextBox1.Text
    Dim SeperatedWords As New List(Of String)
    ' ToList function converts the array to a list.
    SeperatedWords = FullText.Split(",").ToList
    ' Reset the text for re-presentation.
    FullText = ""
    ' Goes through all the seperated words and assign them to FullText with a new line.
    For Each Word As String In SeperatedWords
        FullText = FullText & Word & Environment.NewLine
    Next
    ' Present the new list in the text box.
    TextBox1.Text = FullText
    

    【讨论】:

      【解决方案2】:
      For i = 0 To arrayText.Length - 1 Step 1
      

      最后一个元素的索引为length of array - 1

      【讨论】:

      • 非常感谢 walter,我是否使用正确的程序在新行中添加每个单词?
      猜你喜欢
      • 2012-06-02
      • 1970-01-01
      • 2021-12-17
      • 2015-06-27
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-02
      相关资源
      最近更新 更多