[2005] What's the best way to change a value in a string?
I have a string:
Code:
myString = "A=Bob, B=Cat, C=Tomato, and the crowd goes wild"
I want to always change C to C=Potato. No matter what already is there (wont always be Tomato).
In VB6 I did this:
Code:
start = InStr(1, UCase(myString), UCase("C=")) + Len("C=")
pos_end = InStr(start + 1, myString, ",")
NewString = Mid(myString, 1, start) & "Potato" & Mid(myString, pos_end)
Which worked fine, but I wondered if there was a better way for VB2005
Re: [2005] What's the best way to change a value in a string?
Here is 1 way you can do it in VB2005, but I'm sure there are others ;)
VB.NET Code:
Dim myString As String = "A=Bob, B=Cat, C=Tomato, and the crowd goes wild"
Dim strResult As String = ""
Dim intStart As Integer = myString.IndexOf("C=")
If intStart > 0 Then
strResult = myString.Substring(0, intStart + 2) & "Potato" & myString.Substring(myString.IndexOf(",", intStart))
End If
MessageBox.Show(strResult)
Re: [2005] What's the best way to change a value in a string?
If you are going to use a list with keys like this take a look at the Dictionary Generic Class.
Hope it helps.
Re: [2005] What's the best way to change a value in a string?
If you have a specific pattern of characters you want replaced you can also use Regex.Replace. If you know for a fact that you want to replace "C=somewordhere" then a Regex is probably the way to go.