StringBuilder.ToString() is adding '\' characters in the beginning and ending of the string

不问归期 提交于 2019-12-12 02:38:52

问题


StringBuilder.ToString() is adding '\' characters in the beginning and ending of the string.

Why is this?

Before calling .ToString() the string doesn't have the '\' character.


回答1:


Are you thinking of these backslashes here?

If so, you are misreading the output: The backslashes are not actually in the string. They are only displayed here to make the representation valid according to C# syntax. If you were to output the string using Console.WriteLine, for example, it would not have backslashes.

To be fair, it is inconsistent. The debug view for the StringBuilder doesn’t have the backslashes, but the one for strings does.




回答2:


StringBuilder does not add any characters besides those you have appended. Perhaps you are looking at the Debug View of a string created by string builder and characters which may need to be escaped have the backslash (\) in front of them for convenience of copying the debug output.

The \ characters are not actually in the string data itself, but rather part of the display of the string.

Edit: here is a test you can run

private static void TestStringBuilder()
{
    StringBuilder builder = new StringBuilder();
    builder.Append(@"""saoetuhasoethuasteuhasoetnuh""");
    foreach (char c in builder.ToString())
    {
        System.Diagnostics.Debug.Assert(c != '\\', "EPIC STRINGBUILDER FAIL");
    }
}



回答3:


What text do you have in the StringBuilder?

The following code just writes out "hello" for me

var sb = new StringBuilder();
sb.Append("hello");
var test = sb.ToString();
Console.WriteLine(test);

Am I missing something?



来源:https://stackoverflow.com/questions/3551898/stringbuilder-tostring-is-adding-characters-in-the-beginning-and-ending-of

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!