How to limit StringBuikder Size

Hi There,

I am creating a StringBuilder in my Constructor. I am trying to read the data and insert in the String Builder. As I am inserting, the StringBuikder Size is growing.

Private Shared MAXLENGTH As Integer = 94

Me.strBuilder = New StringBuilder(New String(" "c, Record.MAXLENGTH))

How can I limit my size to 94 characters even if I insert characters.

Please advice.

Thanks

thearthaAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Carlos VillegasFull Stack .NET DeveloperCommented:
After append text to your String Builder you can use the Length property to truncate it content:
Me.strBuilder.Length = 94;

Open in new window


Reference:
http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.length.aspx
Carlos VillegasFull Stack .NET DeveloperCommented:
Remove the ; from the example (C# stuff)
Jacques Bourgeois (James Burger)PresidentCommented:
One of the constructors of the StringBuilder lets you specify it's capacity:

strBuilder=New System.Text.StringBuilder(MAXLENGHT)

Mixing that with the code you posted, you might be looking for something like this instead...

strBuilder = New StringBuilder(New String(" "c, Record.MAXLENGTH),MAXLENGTH)

...HOWEVER

Since you initialize it with a String that is already 94 characters long, the StringBuilder is already completely filled in. So any Insert will add one character and it will bomb on you because it will become too long for the specified capacity.

Maybe you should use my first line of code, and built it from scratch.

The second piece of code could be used, but you would need to use Replace instead of Insert, to replace the spaces instead of inserting between them.

Become a Microsoft Certified Solutions Expert

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

Carlos VillegasFull Stack .NET DeveloperCommented:
Hello @James
If the number of characters to be stored in the current instance exceeds this capacity value, the StringBuilder object allocates additional memory to store them.
Reference:
http://msdn.microsoft.com/en-us/library/zb91weab.aspx
Jacques Bourgeois (James Burger)PresidentCommented:
You are right yv989c, thanks for the correction.

This points to an error in the code I posted. It should have been

strBuilder=New System.Text.StringBuilder(MAXLENGHT, MAXLENGHT)

The first parameter is capacity to set up front, and the second one is the maximum capacity permitted. That will prevent the StringBuilder from going over 94, which was the request anyway if I read the question correctly.

The second one would not work either because as you said, the buffer would be extended without setting the maximum capacity. It would need to be replaced by the following 2 lines:

strBuilder=New System.Text.StringBuilder(MAXLENGHT, MAXLENGHT)
strBuilder.Append(New String(" "c, MAXLENGTH))

And by the way, the Record in front of Record.MAXLENGTH is not needed. Since MAXLENGTH is Private, it does not need any qualifier to call it.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Naman GoelPrinciple Software engineerCommented:
You can use something like This

 StringBuilder sb = new StringBuilder(0,MAXLENGHT);

and you can use following method for appending text

 
private bool AppendValueToStringBuilder(StringBuilder sb, string value)
        {
            bool isAppended = false;
            int requieredCapacity=value.Length + sb.Length;
            if (requieredCapacity > sb.MaxCapacity)
            {
                int noOfCharswillbeInserted = requieredCapacity - sb.MaxCapacity;
                sb.Append(value, 0, noOfCharswillbeInserted);
                isAppended = false;
            }
            else if (requieredCapacity <= sb.MaxCapacity)
            {
                sb.Append(value);
                isAppended = false;
            }
            else
            {
                isAppended = false;
            }
            return isAppended;
        }

Open in new window

Naman GoelPrinciple Software engineerCommented:
following is the method is VB.NET:

StringBuilder sb = new StringBuilder(0,MAXLENGHT)

 
Private Function AppendValueToStringBuilder(sb As StringBuilder, value As String) As Boolean
	Dim isAppended As Boolean = False
	Dim requieredCapacity As Integer = value.Length + sb.Length
	If requieredCapacity > sb.MaxCapacity Then
		Dim noOfCharswillbeInserted As Integer = requieredCapacity - sb.MaxCapacity
		sb.Append(value, 0, noOfCharswillbeInserted)
		isAppended = False
	ElseIf requieredCapacity <= sb.MaxCapacity Then
		sb.Append(value)
		isAppended = False
	Else
		isAppended = False
	End If
	Return isAppended
End Function

Open in new window

thearthaAuthor Commented:
@JamesBurger:

I could limit the size of the Stringbuilder using
Private Shared MAXLENGTH As Integer = 94

Me.strBuilder = New StringBuilder(Record.MAXLENGTH, Record.MAXLENGTH)

but I am unable to insert or append a value at a particular position.

            Dim padLength As Integer = 3
            Dim i As Integer

           Me.strBuilder.Append(CStr(0), startPosition, padLength) ......
' startPosition is 45, padLength is 3. So I am trying to insert 3 zero's at 45,46 and 47th position

Is that possible? Is there any other way.

Thanks.

Naman GoelPrinciple Software engineerCommented:
use

sb.Insert(45,"000")
thearthaAuthor Commented:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: startIndex
Naman GoelPrinciple Software engineerCommented:
this will work only when you are having atleast 45 chars in StringBuilder, because we are trying to insert at 45 position.
thearthaAuthor Commented:
I don't have 44 character filled yet. I filled 30 characters and trying to fill 45,46,47 characters.
Naman GoelPrinciple Software engineerCommented:
then Append() should work.
Naman GoelPrinciple Software engineerCommented:
do something like

sb.Append("abc".PadLeft(14,'0'));
Jacques Bourgeois (James Burger)PresidentCommented:
If you have a StringBuilder set to a maximum capacity of 94, you won't be able have a String longer than that in the StrinBuilder.

If the String is empty at the start, you will be able to Append into it up to 94 characters. But you will not be able to insert into a position until that position has been filled through Append. You cannot Insert at position 23 if the String is "Hi Everybody", because  there is nothing at position 23. Both New StringBuilder(Record.MAXLENGTH, Record.MAXLENGTH) and New StringBuilder(0, Record.MAXLENGTH) give you that condition.

If the String is completely filled in at the start, such as with New StringBuilder(New String(" "c, Record.MAXLENGTH),MAXLENGTH), then there is no way to Insert or Append anywhere, because the String is already 94 characters long. Any Insert or Append would make it longer than 94, which is forbidden by the second parameter.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.