Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prepend to a StringBuilder?

VB.NET have a method, just like java, to append to an object of type StringBuilder But can I prepend to this object (I mean a add some string before the stringbuilder value, not after). Here is my code:

'Declare an array
    Dim IntegerList() = {24, 12, 34, 42}
    Dim ArrayBefore As New StringBuilder()
    Dim ArrayAfterRedim As New StringBuilder()
    ArrayBefore.Append("{")
    For i As Integer = IntegerList.GetLowerBound(0) To IntegerList.GetUpperBound(0)
        ArrayBefore.Append(IntegerList(i) & ", ")
    Next
    ' Close the string
    ArrayBefore.Append("}")
    'Redimension the array (increasing the size by one to five elements)
    'ReDim IntegerList(4)

    'Redimension the array and preserve its contents
    ReDim Preserve IntegerList(4)

    ' print the new redimesioned array
    ArrayAfterRedim.Append("{")
    For i As Integer = IntegerList.GetLowerBound(0) To IntegerList.GetUpperBound(0)
        ArrayAfterRedim.Append(IntegerList(i) & ", ")
    Next
    ' Close the string
    ArrayAfterRedim.Append("}")

    ' Display the two arrays

    lstRandomList.Items.Add("The array before: ")
    lstRandomList.Items.Add(ArrayBefore)
    lstRandomList.Items.Add("The array after: ")
    lstRandomList.Items.Add(ArrayAfterRedim)

If you look at the last 4 lines of my code, I want to add the text just before the string builder all in one line in my list box control. So instead of this:

 lstRandomList.Items.Add("The array before: ")
    lstRandomList.Items.Add(ArrayBefore)

I want to have something like this:

lstRandomList.Items.Add("The array before: " & ArrayBefore)
like image 206
Amaynut Avatar asked Dec 02 '22 19:12

Amaynut


1 Answers

You can use StringBuilder.Insert to prepend to the string builder:

Dim sb = New StringBuilder()
sb.Append("World")
sb.Insert(0, "Hello, ")
Console.WriteLine(sb.ToString())

This outputs:

Hello, World

EDIT

Oops, noticed @dbasnett said the same in a comment...

like image 170
Mark Avatar answered Dec 26 '22 11:12

Mark