• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 469
  • Last Modified:

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

0
theartha
Asked:
theartha
  • 6
  • 3
  • 3
  • +1
1 Solution
 
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
0
 
Carlos VillegasFull Stack .NET DeveloperCommented:
Remove the ; from the example (C# stuff)
0
 
Jacques Bourgeois (James Burger)Commented:
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.

0
Configuration Guide and Best Practices

Read the guide to learn how to orchestrate Data ONTAP, create application-consistent backups and enable fast recovery from NetApp storage snapshots. Version 9.5 also contains performance and scalability enhancements to meet the needs of the largest enterprise environments.

 
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
0
 
Jacques Bourgeois (James Burger)Commented:
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.
0
 
Naman GoelCommented:
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

0
 
Naman GoelCommented:
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

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

0
 
Naman GoelCommented:
use

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

sb.Append("abc".PadLeft(14,'0'));
0
 
Jacques Bourgeois (James Burger)Commented:
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.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 6
  • 3
  • 3
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now