Harison Matondang Harison Matondang - 2 months ago 11x
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)

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

How i can create the result like this :


for the next loop it will be like this :


for the next loop it will be like this :


Thank you


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)

  End Sub
End Class

enter image description here