Question

I would like to create a stringbuilder with the length of 256, and the string "128" should be placed at the start.

However, my code

    Dim sb As New StringBuilder
    sb.Append(New String("128", 256))

    Dim s As String = sb.ToString

shows me that all 256 chars are filled with "1":

s = "1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"

Can somebody tell me what I did wrong? Thank you!

Was it helpful?

Solution

If I'm reading your question right, this should do what you want:

Dim sb As New StringBuilder(256)
sb.Append("128")

Or did you want spaces?

Dim sb As New StringBuilder("128".PadRight(256))

The 256 in the StringBuilder constructor is a performance optimization. Since you know the length of the resulting string, go ahead and reserve all the space for it up front. It's also possible you'll be doing a lot more work to this string, such that a different (larger) number or no number may be appropriate there.


Based on the comment:

    Dim sb As New StringBuilder("128".PadRight(256, NullChar()))

But this is a really bad idea. Don't use nul characters in .Net.

OTHER TIPS

What you did wrong was assume what New String("128", 256) does. If you look at the nearest available constructor: String Constructor (Char, Int32) you will see it takes a Char. This means it ends up repeating the first char, 1, 256 times.

The way you appear to want to do it could be realised using

Dim sb As New StringBuilder("128")
sb.Length = 256

because according to the documentation on the StringBuilder.Length Property: "If the specified length is greater than the current length, the end of the string value of the current StringBuilder object is padded with the Unicode NULL character (U+0000)."

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top