StringBuilder 在實際開發中有許多應用場景,主要用于處理字符串拼接、修改和優化性能。以下是一些常見的應用場景:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
sb.Append("Hello, World!");
}
string result = sb.ToString();
StringBuilder sb = new StringBuilder("Hello, World!");
sb.Replace("World", "C#");
sb.Remove(7, 5);
string result = sb.ToString(); // 輸出 "Hello, C#"
StringBuilder sb = new StringBuilder();
sb.Append("<html><head><title>Example</title></head>");
sb.Append("<body><h1>Hello, World!</h1>");
sb.Append("</body></html>");
string html = sb.ToString();
StringBuilder sb = new StringBuilder();
string result = ComputeExpensiveResult(sb);
StringBuilder sb = new StringBuilder();
sb.AppendLine("Timestamp: " + DateTime.Now);
sb.AppendLine("Message: An error occurred");
string log = sb.ToString();
File.WriteAllText("log.txt", log);
總之,在實際開發中,當需要處理大量字符串操作時,使用 StringBuilder 可以提高性能,減少內存分配和垃圾回收的開銷。