How to remove all characters from StringBuilder in C#

StringBuilder.Clear Method is used to remove all the characters from the current StringBuilder instance.

Syntax:

public System.Text.StringBuilder Clear ();

It returns an StringBuilder object whose length will be zero.

Note:

  • Clear is a convenience method that is equivalent to setting the Length property of the current instance to 0 (zero).
  • Calling the Clear method does not modify the current instance’s Capacity or MaxCapacity property.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to demonstrate
// the Clear() Method
using System;
using System.Text;
  
class GFG {
  
    // Main Method
    public static void Main(String[] args)
    {
        // Creating a StringBuilder object
        StringBuilder sb1 = new StringBuilder("GeeksforGeeks");
  
        // printing the length of "GeeksforGeeks"
        Console.WriteLine("The String is: {0} \nTotal characters -- {1}",
                                             sb1.ToString(), sb1.Length);
  
        // using the method
        sb1.Clear();
  
        // printing the length of "GeeksforGeeks"
        Console.WriteLine("The String is: {0} \nTotal characters -- {1}",
                                             sb1.ToString(), sb1.Length);
  
        sb1.Append("This  is C# Tutorials.");
  
        // printing the length of "GeeksforGeeks"
        Console.WriteLine("The String is: {0} \nTotal characters -- {1}",
                                             sb1.ToString(), sb1.Length);
    }
}

chevron_right


Output:

The String is: GeeksforGeeks 
Total characters -- 13
The String is:  
Total characters -- 0
The String is: This  is C# Tutorials. 
Total characters -- 22

Reference:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.