在标签中显示 for 循环输出的正确方法

Correct way to show an output from for loop in a label

您好,我有一段代码可以使用 for 循环转换字符串数组中每个元素的小写字母。问题是只有最后一个元素出现在输出(标签)上,但在调试输出上显示正常

    Dim lst() = {"apple", "banana", "cherry"}

    For Each item As String In lst
        Dim array() As Char = item.ToCharArray
        array(0) = Char.ToUpper(array(0))

        Dim newS = New String(array)
        Dim value As String = String.Join("/", newS)
        TextBox1.Text = value
        Debug.Write(value)

        Output.Text = value
    Next
    Debug.WriteLine("")

这是出现的问题,它将标签更改为 an 到最后一个大写字母的元素,因为它应该是,但是 我希望输出与调试输出相同

苹果香蕉樱桃

您不需要显式定义 Char 数组。一个字符串有一个 Char(index) 属性 也就是 Default 属性。我们可以直接在 String 上使用它。 MyString(index)

我们将 Replace 方法返回的新 String 分配给数组的一个元素。 index0 开始,整数的默认值,并在 For Each 循环的每次迭代中递增。

最后,在 For Each 之后,我们将 Join 分配给标签。

您的代码及其出错的地方。

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    Dim lst() = {"apple", "banana", "cherry"}

    For Each item As String In lst
        Dim array() As Char = item.ToCharArray
        array(0) = Char.ToUpper(array(0))

        Dim newS = New String(array)
        Dim value As String = String.Join("/", newS)
        TextBox1.Text = value 'Overwrites the last value you assigned to the Text property
        Debug.Write(value) 'Adds on to the last value it wrote in the debug window.

        Label1.Text = value 'Overwrites the last value you assigned to the Text property
    Next
    Debug.WriteLine("")
End Sub

更正代码。

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Dim lst = {"apple", "banana", "cherry"}
    Dim index As Integer
    For Each item As String In lst
        lst(index) = item.Replace(item(0), Char.ToUpper(item(0)))
        index += 1
    Next
    Label1.Text = String.Join("", lst)
End Sub

这是 WinForms,但您关心的代码应该没有任何不同,只是事件过程格式。

您甚至可以在没有显式循环的情况下将其写在一行中。

Dim lst = {"apple", "banana", "cherry"}
Output.Text = String.Join("", lst.Select(Function(x) CultureInfo.CurrentCulture.TextInfo.ToTitleCase(x))))

虽然它看起来很“聪明”,但有几点需要考虑。

  • 如果原始列表很大(意思是几千个字符串)这个 效率较低,因为 Linq Select 和后续的 Join 将创建一个新列表,使使用的内存加倍。

  • 如果要改变不止第一个字符,ToTitleCase 方法无效