Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Clear a StringBuilder in C#
To clear a StringBuilder, use the Clear() method.
Let’s say we have set the following StringBuilder −
string[] myStr = { "One", "Two", "Three", "Four" };
StringBuilder str = new StringBuilder("We will print now...").AppendLine();
Now, use the Clear() method to clear the StringBuilder −
str.Clear();
Let us see the complete code −
Example
using System;
using System.Text;
public class Demo {
public static void Main() {
// string array
string[] myStr = { "One", "Two", "Three", "Four" };
StringBuilder str = new StringBuilder("We will print now...").AppendLine();
// foreach loop to append elements
foreach (string item in myStr) {
str.Append(item).AppendLine();
}
Console.WriteLine(str.ToString());
int len = str.Length;
Console.WriteLine("Length: "+len);
// clearing
str.Clear();
int len2 = str.Length;
Console.WriteLine("Length after using Clear: "+len2);
Console.ReadLine();
}
}
Output
We will print now... One Two Three Four Length: 40 Length after using Clear: 0
Advertisements