C# StringBuilder:如何获得最终的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/227743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
StringBuilder: how to get the final String?
提问by Mister Dev
Someone told me that it's faster to concatenate strings with StringBuilder. I have changed my code but I do not see any Properties or Methods to get the final build string.
有人告诉我用 StringBuilder 连接字符串会更快。我已经更改了我的代码,但我没有看到任何属性或方法来获取最终构建字符串。
How can I get the string?
我怎样才能得到字符串?
采纳答案by Patrick Desjardins
You can use .ToString()
to get the String
from the StringBuilder
.
您可以使用.ToString()
,以获得String
从StringBuilder
。
回答by BlackWasp
Once you have completed the processing using the StringBuilder, use the ToString method to return the final result.
使用 StringBuilder 完成处理后,使用 ToString 方法返回最终结果。
From MSDN:
来自 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
回答by smaclell
I would just like to throw out that is may not necessarily faster, it will definitely have a better memory footprint. This is because string are immutable in .NET and every time you change a string you have created a new one.
我只想抛出它可能不一定更快,它肯定会有更好的内存占用。这是因为字符串在 .NET 中是不可变的,每次更改字符串时都会创建一个新字符串。
回答by Tony Lee
It's not faster to concat - As smaclell pointed out, the issue is the immutable string forcing an extra allocation and recopying of existing data.
连接并没有更快 - 正如 smaclell 所指出的,问题是不可变字符串强制额外分配和重新复制现有数据。
"a"+"b"+"c" is no faster to do with string builder, but repeated concats with an intermediate string gets faster and faster as the # of concat's gets larger like:
"a"+"b"+"c" 与字符串生成器相比并没有更快,但是随着 concat 的 # 变大,使用中间字符串重复连接变得越来越快,例如:
x = "a"; x+="b"; x+="c"; ...
x = "a"; x+="b"; x+="c"; ...
回答by Bill K
About it being faster/better memory:
关于它更快/更好的内存:
I looked into this issue with Java, I assume .NET would be as smart about it.
我用 Java 研究了这个问题,我认为 .NET 会很聪明。
The implementation for String is pretty impressive.
String 的实现令人印象深刻。
The String object tracks "length" and "shared" (independent of the length of the array that holds the string)
String 对象跟踪“长度”和“共享”(与保存字符串的数组长度无关)
So something like
所以像
String a = "abc" + "def" + "ghi";
can be implemented (by the compiler/runtime) as:
可以(由编译器/运行时)实现为:
- Extend the array holding "abc" by 6 additional spaces. - Copy def in right after abc - copy ghi in after def. - give a pointer to the "abc" string to a - leave abc's length at 3, set a's length to 9 - set the shared flag in both.
Since most strings are short-lived, this makes for some VERY efficient code in many cases. The case where it's absolutely NOT efficient is when you are adding to a string within a loop, or when your code is like this:
由于大多数字符串都是短暂的,因此在许多情况下这会产生一些非常有效的代码。绝对无效的情况是当您在循环中添加字符串时,或者当您的代码是这样的:
a = "abc";
a = a + "def";
a += "ghi";
In this case, you are much better off using a StringBuilder construct.
在这种情况下,最好使用 StringBuilder 构造。
My point is that you should be careful whenever you optimize, unless you are ABSOLUTELY sure that you know what you are doing, AND you are absolutely sure it's necessary, AND you test to ensure the optimized code makes a use case pass, just code it in the most readable way possible and don't try to out-think the compiler.
我的观点是,无论何时优化都应该小心,除非您绝对确定自己知道自己在做什么,并且绝对确定这是必要的,并且您进行测试以确保优化的代码通过用例,只需对其进行编码以最易读的方式进行,不要试图超越编译器。
I wasted 3 days messing with strings, caching/reusing string-builders and testing speed before I looked at the string source code and figured out that the compiler was already doing it better than I possibly could for my use case. Then I had to explain how I didn't REALLY know what I was doing, I only thought I did...
在查看字符串源代码并发现编译器已经比我的用例做得更好之前,我浪费了 3 天来处理字符串、缓存/重用字符串构建器和测试速度。然后我不得不解释我怎么不知道我在做什么,我只是以为我知道......
回答by Michael Burr
When you say "it's faster to concatenate String with a String builder", this is only true if you are repeatedly(I repeat - repeatedly) concatenating to the same object.
当您说“将 String 与 String builder 连接起来更快”时,只有当您重复(我重复 -重复)连接到同一个对象时,这才是正确的。
If you're just concatenating 2 strings and doing something with the result immediately as a string
, there's no point to using StringBuilder
.
如果您只是连接 2 个字符串并立即将结果作为 a 执行某些操作string
,那么使用StringBuilder
.
I just stumbled on Jon Skeet's nice write up of this: http://www.yoda.arachsys.com/csharp/stringbuilder.html
我只是偶然发现了 Jon Skeet 写得很好:http: //www.yoda.arachsys.com/csharp/stringbuilder.html
If you are using StringBuilder
, then to get the resulting string
, it's just a matter of calling ToString()
(unsurprisingly).
如果您正在使用StringBuilder
,那么要获得结果string
,这只是一个调用的问题ToString()
(不出所料)。