C# StringBuilder with programming Examples

Description:

C# StringBuilder with programming Examples: in this article, I am going to show you how to use StringBuilder in c# programming with a step-by-step Explanation.


What is a StringBuilder C#?

A StringBuilder class (from the System.Text namespace) allows you to directly manipulate a string without having to create intermediate string objects.

 As a reminder, the functions of the String class never modify the string object on which they operate. They always return another string object, which can be cumbersome and inefficient, especially if the application mainly handles character strings. Think for example of the function Replace which does not modify the object but returns another string object (which then forces to copy the newly created object into the original chain).

The C# StringBuilder class, by operating on the object itself, is more efficient if one performs a lot of manipulation on a chain. Except for simple transactions, transactions on C# StringBuilder objects are two to three times faster than equivalent object operations String.

Let’s introduce the main properties and methods of the C# StringBuilder class. A String object Builder can be indexed, both read and write, for access to a character of the StringBuilder object. During execution, an area of ​​memory is assigned to the String object-Builder for his chain manipulations. The size of this memory area is called “capacity” of the object (Capacity property). Fortunately, this capacity can increase automatically by depending on the operations carried out. These reorganizations, when they do take place, come at a cost, however. Hence the advantage of forcing sufficient capacity so as to avoid or at least limit reorganizations say automatically.



Creating a C# StringBuilder Object:

Unlike the String class, the CLR’s C# StringBuilder class represents nothing special. Also, most languages​​(including C#) do not consider StringBuilder primitive type. The C# StringBuilder object is instantiated in the same way as any object of a non-primitive type:

The C# StringBuilder type has several constructors. The task of each of them is to share memory and initialize three internal fields controlled by any StringBuilder object.

Maximum capacity:

Maximum capacity is an Int32 field that specifies the maximum number of characters to fit in a line. By default it is equal to Int32.MaxValue (about two billion). This value usually does not change, although you can set a smaller value that limits the size of the generated strings. This field cannot be changed for an already created C# StringBuilder object.

Capacity:

Capacity is an Int32 field that indicates the size of the character array StringBuilder. By default, it is 16. If you know how many characters supposed to be placed in C# StringBuilder, specify this number when creating the C# StringBuilder object. When adding characters, StringBuilder determines whether the new size of the array exceeds the specified limit. If yes, then C# StringBuilder automatically doubles the capacity, and based on this value, allocates memory for a new array, and then copies characters from the original array to the new one. The original array is later reclaimed by the garbage collector. Expanding an array dynamically decreases performance, so it should be avoided by setting a suitable capacity at the beginning of work with the object.

character array:

A Character array is an array of Char structures containing a set of “strings” characters. The number of characters is always less than (or equal to) the capacity and maximum capacity. The number of characters in a line can be obtained through the Length property of type StringBuilder. Length is always less or equals to the capacities of the C# StringBuilder. When you create a C#  StringBuilder, you can initialize an array of characters by passing a String to it as a parameter. If no string is given, the array initially contains no characters and the Length property returns 0.


Members of type C# StringBuilder:

The C# StringBuilder type, unlike String, represents a mutable string. This is a sign cheat that many members of StringBuilder modify the content in the character array, without creating new objects allocated on the managed heap. C#  StringBuilder allocates memory for new objects only in two cases:

  • when dynamically building a string that exceeds the specified size new capacity;
  • when calling the ToString method of type StringBuilder.

Constructors of the C# StringBuilder class:

Constructors Description
StringBuilder(); Constructor without argument. A zone of sixteen characters is then automatically allocated. When this StringBuilder object will be handled (by adding or modifying number of characters), no memory reallocation will be necessary as long as we will stay within the limits of the buffer allocated to the chain.
StringBuilder(String); Constructor from a String object.
StringBuilder(int); The initial capacity of the chain is given, which will avoid reorganizations (allocation of a new memory area, copy and free) as long as this capacity is not outdated.
StringBuilder (String, int); Same thing but the buffet is initialized with a character string. The second argument gives the initial capacity of the string.

 

Properties of the C# StringBuilder class:

Properties Description
Length int Number of characters in the StringBuilder object.


Methods of the C#  StringBuilder class:

Methods Description
StringBuilder Append(type): Adds information to the end of the object on which Append operates. The argument can be of type byte, sbyte, short, char, bool, string, int, uint, long, ulong, float, double and even any object (then redefine the object’s ToString method). See the note below regarding the StringBuilder object returned by the function.
StringBuilder

Insert(int pos, type);

Inserts one of the previous types starting from the second position in the object on which operates the function.
StringBuilder Remove( int startIndex, int length); Removes length characters from the startIndex position.
StringBuilder Replace( string s1, string s2); Replaces all occurrences of s1 by s2 (modifications made directly in the object).
StringBuilder Replace( string s1, string s2, int startIndex, int count); Same thing but the search for s1 is only performed on count characters at from the startIndex position.
string ToString(); Returns a String object corresponding to the contents of the StringBuilder object.
Chars Returns from an array or sets the character at the given index in the array. In C #, this is an indexer property (a property with a parameter), which is accessed as elements of an array. (using square brackets [])
Clear Clears the contents of the StringBuilder object, similar to setting the Length property to 0
AppendFormat Adds the given objects to a character array, increasing it if necessary. Objects are converted to a string of the specified format and taking into account given regional standards. This is one of the most commonly used methods when working with StringBuilder objects
AppendLine Append an empty string to the end of a character array, increasing its capacity if necessary
CopyTo Copies a subset of StringBuilder characters to array Char
MaxCapacity Returns the largest number of characters which can be placed in line
Capacity Gets / sets the size of an array characters. When trying to install capacity less than the length of the line, or more, than MaxCapacity, an exception is thrown ArgumentOutOfRangeException
EnsureCapacity Ensures that the size of the character array will be not less than the value of the parameter passed this method. If the value exceeds the current the capacity of the StringBuilder object, the size of the array increases. If the current capacity is greater than the value passed to this property does not change the size of the array
Replace Replaces one character or character string in a character array
Remove Removes a range of characters from a character array
Equals Returns true only if StringBuilder objects have the same maximum capacity, capacity, and identical characters in an array


One important thing to note is that most of the C# StringBuilder methods return a reference to the same StringBuilder object. This allows you to build several operations in a chain at once:

The C# StringBuilder class does not have some analogs for the methods of the String class. For example, the String class has methods ToLower, ToUpper, EndsWith, PadLeft, Trim, and so on, which the StringBuilder class does not have. At the same time, the StringBuilder class there is an extended Replace method that replaces characters and strings only in part of a line (not in the whole line). Due to the lack of full compliance between methods sometimes you have to resort to conversions between String and StringBuilder. For example, form a string, capitalize all letters, and then inserting another line into it allows the following code:

Example: C# Stringbuilder appendformat for String Manipulation:

Output:



Program Explanation:

This line of code is used to Do some string manipulation using StringBuilder

this statement is used to Convert StringBuilder to String, to make all characters uppercase

this statement is used to Clear the StringBuilder (memory is allocated for the new Char array)

this statement is used to Load the string with uppercase String into the StringBuilder and perform the rest of the operations

This statement is used to Convert StringBuilder back to String

As you know that this statement is used to Display the String to the screen for the user

Example: How to use the StringBuilder Replace in C#:

Output:


Immutable strings:

a string created once cannot be made longer or shorter, it cannot be change any characters. Consistency of strings has certain advantages. To begin with, you can perform operations on strings without changing them:

Here ToUpperInvariant returns a new string; characters in string s do not change. SubString handles the string returned by ToUpperInvariant and also returns a new string, which is then passed to the EndsWith method. There are no references to the two temporary strings created in the application code. ToUpperInvariant and SubString, so the memory they occupied will be freed when next garbage collection. If a lot of string operations are performed, on the heap a lot of String objects are created – this forces you to use the garbage collector more often, which negatively affects the performance of the application.

Due to the immutability of strings, there is no problem of thread synchronization when working with strings. Also, in the CLR, multiple String references can indicate to one rather than several different string objects if the strings are identical. This means that you can reduce the number of lines in the system and reduce memory consumption – this is exactly what directly relates to string interning (string interning), which will be discussed later.

For performance reasons, the String type is tightly integrated with the CLR. In particular, the CLR “knows” the exact location of the fields in this type and addresses to them directly. Performance improvements and direct access account for pay a small price: the String class is sealed. Otherwise, having the opportunity to describe a native type derived from String, one could add own fields that contradict the String structure and break the CLR. Besides additionally, your actions might violate the CLR’s assumptions about the String object, which follow from its immutability.


C# StringBuilder Programming Examples:

Example: C# Stringbuilder remove last character:

output:

Example: C# stringbuilder with parameters:

Output:


Example: C# stringbuilder insert performance:

Output:

Example: How to use C# stringbuilder append:

Output:



Example: how to use c# stringbuilder indexof:

Output:

 

Recommended For You

About the Author: Fawad

My name is Shahzada Fawad and I am a Programmer. Currently, I am running my own YouTube channel "Expertstech", and managing this Website. My Hobbies are * Watching Movies * Music * Photography * Travelling * gaming and so on...

Leave a Reply

%d bloggers like this: