NET works. Rather than needing. ToString all the time. Also, before you say "just inherit StringBuilder and extend it", it's sealed. I didn't implement all the overloads of the.
This can literally be used in the exact same manner as the. Append , and you can implicitly convert it to a string.
You can use the see tag's cref attribute. If you generate documentation, some tools will generate hyperlinks for you. The length property of a StringBuilder is read and writable. It's also really useful for it to be so:. That's a contrived example which is trivially served with string. Join but setting the length can be useful!
I'd say CurrentString is superflous. Sign up to join this community. The best answers are voted up and rise to the top. Stack Overflow for Teams — Collaborate and share knowledge with a private group. When you have to perform extensive search operations while you are building your string. You'll have to convert the StringBuilder object to a String for these operations, and this can negate the performance benefit from using StringBuilder.
For more information, see the Searching the text in a StringBuilder object section. Consider using the StringBuilder class under these conditions:. When you expect your code to make an unknown number of changes to a string at design time for example, when you are using a loop to concatenate a random number of strings that contain user input. The StringBuilder. Length property indicates the number of characters the StringBuilder object currently contains.
If you add characters to the StringBuilder object, its length increases until it equals the size of the StringBuilder. Capacity property, which defines the number of characters that the object can contain.
If the number of added characters causes the length of the StringBuilder object to exceed its current capacity, new memory is allocated, the value of the Capacity property is doubled, new characters are added to the StringBuilder object, and its Length property is adjusted. Additional memory for the StringBuilder object is allocated dynamically until it reaches the value defined by the StringBuilder.
MaxCapacity property. When the maximum capacity is reached, no further memory can be allocated for the StringBuilder object, and trying to add characters or expand it beyond its maximum capacity throws either an ArgumentOutOfRangeException or an OutOfMemoryException exception. The following example illustrates how a StringBuilder object allocates new memory and increases its capacity dynamically as the string assigned to the object expands.
The code creates a StringBuilder object by calling its default parameterless constructor. The default capacity of this object is 16 characters, and its maximum capacity is more than 2 billion characters. Appending the string "This is a sentence.
The capacity of the object doubles to 32 characters, the new string is added, and the length of the object now equals 19 characters. The code then appends the string "This is an additional sentence.
Whenever the append operation causes the length of the StringBuilder object to exceed its capacity, its existing capacity is doubled and the Append operation succeeds. The default capacity of a StringBuilder object is 16 characters, and its default maximum capacity is Int You can explicitly define the initial capacity of a StringBuilder object in the following ways:.
By calling any of the StringBuilder constructors that includes a capacity parameter when you create the object. By explicitly assigning a new value to the StringBuilder. Capacity property to expand an existing StringBuilder object. Note that the property throws an exception if the new capacity is less than the existing capacity or greater than the StringBuilder object's maximum capacity. By calling the StringBuilder. EnsureCapacity method with the new capacity. The new capacity must not be greater than the StringBuilder object's maximum capacity.
However, unlike an assignment to the Capacity property, EnsureCapacity does not throw an exception if the desired new capacity is less than the existing capacity; in this case, the method call has no effect. If the length of the string assigned to the StringBuilder object in the constructor call exceeds either the default capacity or the specified capacity, the Capacity property is set to the length of the string specified with the value parameter.
You can explicitly define the maximum capacity of a StringBuilder object by calling the StringBuilder Int32, Int32 constructor. You can't change the maximum capacity by assigning a new value to the MaxCapacity property, because it is read-only. As the previous section shows, whenever the existing capacity is inadequate, additional memory is allocated and the capacity of a StringBuilder object doubles up to the value defined by the MaxCapacity property. In general, the default capacity and maximum capacity are adequate for most apps.
You might consider setting these values under the following conditions:. If the eventual size of the StringBuilder object is likely to grow exceedingly large, typically in excess of several megabytes. In this case, there may be some performance benefit from setting the initial Capacity property to a significantly high value to eliminate the need for too many memory reallocations. If your code is running on a system with limited memory. In this case, you may want to consider setting the MaxCapacity property to less than Int MaxValue if your code is handling large strings that may cause it to execute in a memory-constrained environment.
You instantiate a StringBuilder object by calling one of its six overloaded class constructors, which are listed in the following table. Three of the constructors instantiate a StringBuilder object whose value is an empty string, but set its Capacity and MaxCapacity values differently. The remaining three constructors define a StringBuilder object that has a specific string value and capacity. Two of the three constructors use the default maximum capacity of Int MaxValue , whereas the third allows you to set the maximum capacity.
The following example uses three of these constructor overloads to instantiate StringBuilder objects. Most of the methods that modify the string in a StringBuilder instance return a reference to that same instance.
This enables you to call StringBuilder methods in two ways:. You can make a series of method calls in a single statement. This can be convenient if you want to write a single statement that chains successive operations.
The following example consolidates three method calls from the previous example into a single line of code. You can use the methods of the StringBuilder class to iterate, add, delete, or modify characters in a StringBuilder object. You can access the characters in a StringBuilder object by using the StringBuilder. Chars[] property. This enables you to set or retrieve individual characters by using their index only, without explicitly referencing the Chars[] property.
Characters in a StringBuilder object begin at index 0 zero and continue to index Length - 1. The following example illustrates the Chars[] property. It appends ten random numbers to a StringBuilder object, and then iterates each character.
If the character's Unicode category is UnicodeCategory. DecimalDigitNumber , it decreases the number by 1 or changes the number to 9 if its value is 0. The example displays the contents of the StringBuilder object both before and after the values of individual characters were changed. Using character-based indexing with the Chars[] property can be extremely slow under the following conditions:. Performance is severely impacted because each character access walks the entire linked list of chunks to find the correct buffer to index into.
Even for a large "chunky" StringBuilder object, using the Chars[] property for index-based access to one or a small number of characters has a negligible performance impact; typically, it is an 0 n operation. If you encounter performance issues when using character-based indexing with StringBuilder objects, you can use any of the following workarounds:.
Convert the StringBuilder instance to a String by calling the ToString method, then access the characters in the string. Copy the contents of the existing StringBuilder object to a new pre-sized StringBuilder object.
Performance improves because the new StringBuilder object is not chunky. For example:. Set the initial capacity of the StringBuilder object to a value that is approximately equal to its maximum expected size by calling the StringBuilder Int32 constructor.
Note that this allocates the entire block of memory even if the StringBuilder rarely reaches its maximum capacity. The StringBuilder class includes the following methods for expanding the contents of a StringBuilder object:.
The Append method appends a string, a substring, a character array, a portion of a character array, a single character repeated multiple times, or the string representation of a primitive data type to a StringBuilder object.
The AppendLine method appends a line terminator or a string along with a line terminator to a StringBuilder object. The AppendFormat method appends a composite format string to a StringBuilder object.
The string representations of objects included in the result string can reflect the formatting conventions of the current system culture or a specified culture. The Insert method inserts a string, a substring, multiple repetitions of a string, a character array, a portion of a character array, or the string representation of a primitive data type at a specified position in the StringBuilder object.
The position is defined by a zero-based index. The StringBuilder class includes methods that can reduce the size of the current StringBuilder instance. The Clear method removes all characters and sets the Length property to zero. The Remove method deletes a specified number of characters starting at a particular index position.
In addition, you can remove characters from the end of a StringBuilder object by setting its Length property to a value that is less than the length of the current instance. The following example removes some of the text from a StringBuilder object, displays its resulting capacity, maximum capacity, and length property values, and then calls the Clear method to remove all the characters from the StringBuilder object.
Replace method replaces all occurrences of a character or a string in the entire StringBuilder object or in a particular character range. The following example uses the Replace method to replace all exclamation points! The StringBuilder class does not include methods similar to the String. Contains , String. IndexOf , and String. StartsWith methods provided by the String class, which allow you to search the object for a particular character or a substring.
Determining the presence or starting character position of a substring requires that you search a String value by using either a string search method or a regular expression method. There are four ways to implement such searches, as the following table shows.
If the goal of the search is to determine whether a particular substring exists that is, if you aren't interested in the position of the substring , you can search strings before storing them in the StringBuilder object. The following example provides one possible implementation. It defines a StringBuilderFinder class whose constructor is passed a reference to a StringBuilder object and the substring to find in the string.
In this case, the example tries to determine whether recorded temperatures are in Fahrenheit or Celsius, and adds the appropriate introductory text to the beginning of the StringBuilder object. A random number generator is used to select an array that contains data in either degrees Celsius or degrees Fahrenheit. Call the StringBuilder. ToString method to convert the StringBuilder object to a String object.
You can search the string by using methods such as String. LastIndexOf or String. StartsWith , or you can use regular expressions and the Regex class to search for patterns. Because both StringBuilder and String objects use UTF encoding to store characters, the index positions of characters, substrings, and regular expression matches are the same in both objects. This enables you to use StringBuilder methods to make changes at the same position at which that text is found in the String object.
If you adopt this approach, you should work from the end of the StringBuilder object to its beginning so that you don't have to repeatedly convert the StringBuilder object to a string.
The following example illustrates this approach. That is, each operation that appears to modify a string object actually creates a new string.
For example, the call to the string. Concat String[] method in the following C example appears to change the value of a string variable named value. In fact, the string. Concat String[] method returns a value object that has a different value and address from the value object that was passed to the method.
For routines that perform extensive string manipulation such as apps that modify a string numerous times in a loop , modifying a string repeatedly can exact a significant performance penalty.
The alternative is to use System. StringBuilder , which is a mutable string class. Mutability means that once an instance of the class has been created, it can be modified by appending, removing, replacing, or inserting characters. A System.
StringBuilder object maintains a buffer to accommodate expansions to the string. New data is appended to the buffer if room is available; otherwise, a new, larger buffer is allocated, data from the original buffer is copied to the new buffer, and the new data is then appended to the new buffer.
Although the System. StringBuilder class generally offers better performance than the string class, you should not automatically replace string with System. StringBuilder whenever you want to manipulate strings. Performance depends on the size of the string, the amount of memory to be allocated for the new string, the system on which your app is executing, and the type of operation. You should be prepared to test your app to determine whether System.
StringBuilder actually offers a significant performance improvement. Consider using the string class under these conditions:. When the number of changes that your app will make to a string is small. In these cases, System. StringBuilder might offer negligible or no performance improvement over string. When you are performing a fixed number of concatenation operations, particularly with string literals. In this case, the compiler might combine the concatenation operations into a single operation.
When you have to perform extensive search operations while you are building your string. The System. You'll have to convert the System. StringBuilder object to a string for these operations, and this can negate the performance benefit from using System.
For more information, see the Searching the text in a StringBuilder object section. Consider using the System. StringBuilder class under these conditions:. When you expect your app to make an unknown number of changes to a string at design time for example, when you are using a loop to concatenate a random number of strings that contain user input.
The StringBuilder. Length property indicates the number of characters the System. StringBuilder object currently contains. If you add characters to the System.
StringBuilder object, its length increases until it equals the size of the StringBuilder. Capacity property, which defines the number of characters that the object can contain. If the number of added characters causes the length of the System. StringBuilder object to exceed its current capacity, new memory is allocated, the value of the StringBuilder.
Capacity property is doubled, new characters are added to the System. StringBuilder object, and its StringBuilder. Length property is adjusted. Additional memory for the System. StringBuilder object is allocated dynamically until it reaches the value defined by the StringBuilder.
MaxCapacity property. When the maximum capacity is reached, no further memory can be allocated for the System. The following example illustrates how a System.
StringBuilder object allocates new memory and increases its capacity dynamically as the string assigned to the object expands. The code creates a System. StringBuilder object by calling its default parameterless constructor. The default capacity of this object is 16 characters, and its maximum capacity is more than 2 billion characters.
Appending the string "This is a sentence. StringBuilder object. The capacity of the object doubles to 32 characters, the new string is added, and the length of the object now equals 19 characters.
The code then appends the string "This is an additional sentence. StringBuilder object 11 times. Whenever the append operation causes the length of the System.
StringBuilder object to exceed its capacity, its existing capacity is doubled and the StringBuilder. Append string operation succeeds. The default capacity of a System.
StringBuilder object is 16 characters, and its default maximum capacity is int. These default values are used if you call the StringBuilder. You can explicitly define the initial capacity of a System. StringBuilder object in the following ways:. By calling any of the System. StringBuilder constructors that includes a capacity parameter when you create the object. By explicitly assigning a new value to the StringBuilder. Capacity property to expand an existing System. Note that the property throws an exception if the new capacity is less than the existing capacity or greater than the System.
StringBuilder object's maximum capacity. By calling the StringBuilder. EnsureCapacity int method with the new capacity. The new capacity must not be greater than the System. However, unlike an assignment to the StringBuilder. Capacity property, StringBuilder. EnsureCapacity int does not throw an exception if the desired new capacity is less than the existing capacity; in this case, the method call has no effect. If the length of the string assigned to the System. StringBuilder object in the constructor call exceeds either the default capacity or the specified capacity, the StringBuilder.
Capacity property is set to the length of the string specified with the value parameter. You can explicitly define the maximum capacity of a System. StringBuilder object by calling the StringBuilder.
0コメント