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 可以提高性能,减少内存分配和垃圾回收的开销。