How To Remove All Characters From Stringbuilder In C#

Before delving into the process of eliminating all characters from a StringBuilder in C#, it is essential to have a comprehensive understanding of what StringBuilder is in the context of C#. Let's explore this concept further.

What is the StringBuilder in C#?

StringBuilder represents a type of string class within the System.Text namespace that enables the direct modification of String objects. This class offers enhanced performance compared to conventional approaches within the System namespace. When utilizing StringBuilder, alterations made to the String object are preserved without modification. To instantiate a blank StringBuilder for temporary storage, employ the new keyword alongside the default constructor.

For instance, the fresh string "Hello World" is stored in the heap memory. Modifying the initial string, "Hello World", to "Hello World String" involves creating a new string object. This differs from altering the original string directly at the existing memory location. Each modification like replacing, adding, deleting, or inserting new strings results in the creation of a new String object, impacting performance adversely.

Syntax:

It has the following syntax:

Example

public System.Text.StringBuilder Clear ()
  • It returns a StringBuilder object with a length of zero.
  • The clear method is a convenient method for setting the Length property of the current instance to 0 (zero).
  • Calling the Clear method does not change the Capacity or MaxCapacity properties of the current instance.
  • Need of StringBuilder:

In C#, the string class objects are unchangeable. When there is a necessity to execute recurring tasks on a string, a StringBuilder becomes essential. It offers an efficient method to manage repetitive multiple-string modification tasks.

Example:

Let's consider a C# code snippet to demonstrate the implementation of the clear method in the StringBuilder class.

Example

Using System; 
Using System.Text; 

class StringClear { 

	// Main Method 
	public static void Main(String[] args) 
	{ 
		//An object obj is created for the StringBuilder class
		StringBuilder obj = new StringBuilder("Programming"); 
		// console statement to print the length of the string
		Console.WriteLine("The input String is: {0} \nThe total length of the string is  
                      -- {1}", obj.ToString(),obj.Length); 
		// using the method 
		obj.Clear(); 
		//console statement to print the length of the string
		Console.WriteLine("The String is: {0} \nThe total length of the string is  -- 
                     {1}", obj.ToString(),obj.Length); 
		obj.Append("This is hello world"); 
		//The length of the string after clear() method
		Console.WriteLine("The given String is: {0} \nThe total length of the string is  
                      --    {1}", obj.ToString(), obj.Length); 
	} 
}

Output:

Output

The input String is: Programming 
The total length of the string is -- 11
The String is:  
The total length of the string is  -- 0
The given String is: This is hello world 
The total length of the string is  -- 18

Explanation:

  • In this example, the program starts with a StringBuilder object named initialised obj with the string "Programming" . The Console.WriteLine specifies the beginning of the string, including its length.
  • After that, the Clear method is called on the obj instance and successfully empties the contents of the StringBuilder . Another WriteLine array is used to display the updated state of the string, indicating empty strings and lengths.
  • Next, the function adds the string "This is a hello world" to the StringBuilder using the Append method. The last Console.WriteLine statement displays the modified string and its updated length.
  • Example 2:

Let's consider another C# program to demonstrate the implementation of the clear method from the StringBuilder class.

Example

using System;
using System.Text;

public class StringClear2 {
   public static void Main() {
      // the initial string array
     string[] st = { "Apple", "Mango", "Banana", "Guava" };
      StringBuilder sts = new StringBuilder("The string entries are..").AppendLine();

      // looping statement to append values
      foreach (string item in st) {
         sts.Append(item).AppendLine();
      }
      Console.WriteLine(sts.ToString());
      int length = sts.Length;
      Console.WriteLine("The length of the string Builder is: "+length);

      // the clear() method to empty string
      sts.Clear();
      int length2 = sts.Length;
      Console.WriteLine("The length of the string after using the clear method: "+length2);
      Console.ReadLine();
   }
}

Output:

Output

The string entries are.
Apple
Mango
Banana
Guava

The length of the string Builder is: 50
The length of the string after using the clear method: 0

Explanation:

In this instance, the code initiates by prepending the string array with the username. The StringBuilder is employed to construct a string by appending each method name within the loop. The script showcases the resultant string and its character count. Subsequently, it employs the Clear function to empty the StringBuilder. Lastly, the StringBuilder verifies its length to ensure clearance, yielding an empty string.

Input Required

This code uses input(). Please provide values below: