有人告诉我,用StringBuilder连接字符串会更快.我已经更改了我的代码,但是我没有看到任何属性或方法来获取最终的构建字符串.
我怎样才能得到这个字符串?
您可以使用.ToString()
,以获得String
从StringBuilder
.
当你说"将字符串与字符串构建器连接起来更快"时,只有当你重复(重复 - 重复)连接到同一个对象时才会这样.
如果您只是将2个字符串连接起来并立即对结果执行某些操作string
,则无需使用StringBuilder
.
我刚刚偶然发现Jon Skeet很好地写了这篇文章:http://www.yoda.arachsys.com/csharp/stringbuilder.html
如果你正在使用StringBuilder
,那么为了得到结果string
,这只是一个问题ToString()
(不出所料).
使用StringBuilder完成处理后,使用ToString方法返回最终结果.
来自MSDN:
using System; using System.Text; public sealed class App { static void Main() { // Create a StringBuilder that expects to hold 50 characters. // Initialize the StringBuilder with "ABC". StringBuilder sb = new StringBuilder("ABC", 50); // Append three characters (D, E, and F) to the end of the StringBuilder. sb.Append(new char[] { 'D', 'E', 'F' }); // Append a format string to the end of the StringBuilder. sb.AppendFormat("GHI{0}{1}", 'J', 'k'); // Display the number of characters in the StringBuilder and its string. Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString()); // Insert a string at the beginning of the StringBuilder. sb.Insert(0, "Alphabet: "); // Replace all lowercase k's with uppercase K's. sb.Replace('k', 'K'); // Display the number of characters in the StringBuilder and its string. Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString()); } } // This code produces the following output. // // 11 chars: ABCDEFGHIJk // 21 chars: Alphabet: ABCDEFGHIJK