Search code examples
vb.netstringbuilder

String Builder Appending value in middle of existing appendage


I have Dims I am referencing to Append a String, however my requirement requests that I split up one of my previous Dims I am appending. Please see the example below to show you what i am trying to get at. Basically i need a way for my newest Dim added to go smack dab in the middle of an existing Dim that's already been appended. **Note: Dim a can be dynamic so I don't know the number of characters it will return.

I am using the StringBuilder functionality in VB.

Dim sb = New StringBuilder()

Dim a = someValueForA

Dim b = someValueForB

Dim c = someValueForC

Dim d = someValueForD

sb.AppendFormat("-{0}",a)
sb.AppendFormat("-{0}",b)
sb.AppendFormat("-{0}",c)

result = "someValueAsomeValueBsomeValueC"

now i need to insert d right in the middle of "C" so as to look something like this:

result = "someValueAsomeValueBsomesomeValueDValueC"

Solution

  • You need to calculate the position and then use sb.Insert:

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
       Dim sb = New StringBuilder()
       Dim a = "someValueA"
       Dim b = "someValueB"
       Dim c = "someValueC"
       Dim d = "someValueD"
    
       sb.AppendFormat("-{0}", a)
       sb.AppendFormat("-{0}", b)
       sb.AppendFormat("-{0}", c)
       sb.Insert(sb.Length - (c.Length \ 2), d)
    
       MessageBox.Show(sb.ToString())
    End Sub