Dexter Dexter - 1 year ago 45
Vb.net Question

Replace instance based on array's index

I'm looking to replace all occurence "[2]" in a given string
Here is my current function

Dim replace() As String
replace = Split("3,2,4,1", ",")
Dim orig As String = "[2] [2] [2] [2]"
Dim search As String = "[2]"
sb = New StringBuilder(orig)
For i As Integer = 0 To replace.Length - 1

Dim Occurrence = sb.ToString().IndexOf(search)
If Occurrence > -1 Then
If (replace(j) = "2") Then
sb.Replace(search, "[2]", firstOccurrence, search.Length)
j = j + 1
Else
sb.Replace(search, "[" & replace(j) & "]", firstOccurrence, search.Length)
j = j + 1
End If
End If

Next


Actually i get this :

Output : [3] [4] [1] [2]


I'm looking to get something like this:

Output : [3] [2] [4] [1]


Thank's

Answer Source

Since you are replacing with what you already have you need to keep track of the start point of your next search each time

Dim Occurrence = sb.ToString().IndexOf(search, Occurance)

And you already know the position so

sb.Replace(search, "[2]", Occurrence, search.Length)

or

sb.Replace(search, "[" & replace(j) & "]", Occurrence, search.Length)

and end with

Occurance += search.Length

And don't use variable names like search and replace in routines like this. It's just confusing.... and looks like function calls. When you come back to your code in six months you will thank me.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download