1

I am having a problem with string replacement. Below is my code as of now. I want to replace each character in textbox1 and write it to textbox2, but this only works for the last character.

If I write:

Hello

Then it should end up as:

[[h]][[e]][[l]][[l]][[o]]

Public Class Form1
    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        Try
            TextBox2.Text = TextBox1.Text.Replace("0"c, "[[something0a0]]")
            TextBox2.Text = TextBox1.Text.Replace("1"c, "[[something1a1]]")
            TextBox2.Text = TextBox1.Text.Replace("2"c, "[[something2a2]]")
            TextBox2.Text = TextBox1.Text.Replace("3"c, "[[something3a3]]")   

        Catch ex As Exception

        End Try
    End Sub
End Class
4

2 回答 2

4

您正在覆盖TextBox2. 改为链接您的Replace呼叫并设置一次分配。

TextBox2.Text = TextBox1.Text.Replace("0"c, "[[something0a0]]")
                             .Replace("1"c, "[[something1a1]]")
                             .Replace("2"c, "[[something2a2]]")
                             .Replace("3"c, "[[something3a3]]")
于 2013-08-06T16:20:35.927 回答
1

您可以这样做的一种方法是使用这样的循环。不确定它是否是最有效的,但它很容易理解:

TextBox2.Text = ""
For Each chr As Char In TextBox1.Text
    TextBox2.Text += "[[" & chr & "]]"
Next

另一种简单的方法是:

TextBox2.Text = "[[" & String.Join("]][[ ", TextBox1.Text.ToCharArray().AsEnumerable()) & "]]"

高温高压

于 2013-08-06T17:11:47.350 回答