Harison Matondang Harison Matondang - 3 months ago 15
Vb.net Question

How to Replace string and loop between commas with another string

can you help me how to get Index of the same string and replace it one by one with another string?

Here my example code :

For i As Integer = 0 To 10
Dim str As String = "abcd,abcd,abcd,abcd,abcd,abcd,abcd,abcd"
Dim replace As String = "efgh"
Dim value As String
value = str.Replace("abcd", replace)
TextBox4.AppendText(value)
Next


The value will be result : efgh,efgh,efgh,efgh,efgh...

How i can create the result like this :

efgh,abcd,abcd,abcd,abcd,abcd...

for the next loop it will be like this :

abcd,efgh,abcd,abcd,abcd,abcd...

for the next loop it will be like this :

abcd,abcd,efgh,abcd,abcd,abcd...

Thank you

Answer

As @Mark mentioned there are lots of ways this could be done. One of this ways to add and remove ranges in a string is to use the StringBuilder.

Imports System.Text

Public Class Form1
  Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    For i As Integer = 0 To 35 Step 5
      Dim sDefaultString As String = "abcd,abcd,abcd,abcd,abcd,abcd,abcd,abcd"
      Dim sbText = New StringBuilder(sDefaultString)
      sbText.Remove(i, 4)
      sbText.Insert(i, "efgh")
      TextBox1.AppendText(sbText.ToString & vbNewLine)
    Next

  End Sub
End Class

enter image description here

Comments