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:
// 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);
}
} |
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: