How to prepend to a StringBuilder?
Asked Answered
E

2

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)
Excusatory answered 7/8, 2014 at 21:37 Comment(3)
Not very clear what the issue is. Try "The array before: " & ArrayBefore.ToString.Metro
Stringbuilder has an Insert method, so if you insert at 0 you are pre-pending.Eradicate
Why are you redimming the array? What are you really trying to do here?Kochi
G
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...

Genip answered 8/8, 2014 at 2:34 Comment(0)
K
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.

Kochi answered 8/8, 2014 at 3:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.