5

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)
Amaynut
  • 4,091
  • 6
  • 39
  • 44

2 Answers2

19

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...

Mark
  • 8,140
  • 1
  • 14
  • 29
0

Your code seems like a lot of overkill to use StringBuilder with those For loops.

Why not do this?

Dim IntegerList() = {24, 12, 34, 42}

lstRandomList.Items.Add("The array before: ")
lstRandomList.Items.Add(String.Format("{{{0}}}", String.Join(", ", IntegerList)))

ReDim Preserve IntegerList(4)

lstRandomList.Items.Add("The array after: ")
lstRandomList.Items.Add(String.Format("{{{0}}}", String.Join(", ", IntegerList)))

Job done. Much simpler code.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172