Darryl Darryl - 1 month ago 9x
Vb.net Question

How do I find and replace a duplicate number in a string and keep one of the duplicate numbers?

I am using Visual Basic 2010

I am trying to find a specific duplicate number in a string and replace it with another number but keep one of the duplicates in the string. For example: the string is

and i need the new string to be
which keeps one of the 8's and the other 8 is replaced by 6. In my code I have it replacing both 8's and result is
. It is replacing both 8's with 6's. Can anyone help? Note: There are two duplicate numbers in this example but the specific duplicate I need is the 8 and not the 2. Also, it does not matter which 8 is replaced or kept. Thank you! Update to this post... The 5 digit string will not always be
. I am using this string as an example. There could even be a string that does not have any 8's at all. I need to check any string that has more than one 8. If it has one 8 then the string does not need to change.

Dim strText As String = "24828"
Dim newStrText As String = ""
Dim nIndex = strText.IndexOf("8")
If nIndex > -1 Then
MessageBox.Show("Found 8")
newStrText = strText.Replace("8", "6")
MessageBox.Show("There is no 8")
End If


I think this works nicely:

Dim text = "24828"

Dim split = text.Split("8"c)
Dim result = If(split.Length > 1, _
    String.Join("6", split.Take(split.Length - 1)) + "8" + split.Last(), _

I get 24628.