StringBuilder.ToString() 正在添加 '\'字符串开头和结尾的字符

发布于 2024-09-16 04:02:18 字数 118 浏览 6 评论 0原文

StringBuilder.ToString() 在字符串的开头和结尾添加“\”字符。

这是为什么呢?

在调用 .ToString() 之前,字符串没有“\”字符。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

╭⌒浅淡时光〆 2024-09-23 04:02:18

您在这里想到这些反斜杠吗?

Watch 窗口中显示反斜杠的示例屏幕截图

如果是这样,则您误读了输出:反斜杠实际上并不在字符串中。它们仅显示在此处,以使表示根据 C# 语法有效。例如,如果您要使用Console.WriteLine 输出字符串,则它不会有反斜杠。

公平地说,这是不一致的。 StringBuilder 的调试视图没有反斜杠,但字符串的调试视图有。

Are you thinking of these backslashes here?

Example screenshot showing backslashes in the Watch window

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.

九命猫 2024-09-23 04:02:18

StringBuilder 不会添加除您所拥有的字符之外的任何字符附加。也许您正在查看由字符串生成器创建的字符串的调试视图和字符可能需要转义,并在其前面添加反斜杠 (\),以便于复制调试输出。

\ 字符实际上并不在字符串数据本身中,而是字符串显示的一部分。

编辑:这是您可以运行的测试

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");
    }
}

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");
    }
}
茶花眉 2024-09-23 04:02:18

StringBuilder 中有什么文本?

下面的代码只是为我写出“hello”,

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

我错过了什么吗?

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文