【问题标题】:Create multi line string object from string array - C#从字符串数组创建多行字符串对象 - C#
【发布时间】:2019-03-20 06:03:04
【问题描述】:

我正在尝试从字符串数组创建多行字符串 喜欢

@"A minErr message has two parts: 
  the message itself and the url that contains the encoded message.
  The message's parameters can contain other error messages which also include error urls.";

我有这些行的字符串数组

string [] miltilines={"A minErr message has two parts:","the message itself and the url that contains the encoded message.","The message's parameters can contain other error messages which also include error urls."}

我尝试了多种方法来获取多行字符串对象,但在字符串对象中以 \r\n 结束

1:String.Join(Environment.NewLine, miltilines)

2:

string multiline = @" ";
foreach (var item in miltilines)
            {
                multiline += @"" + item.Trim() + " ";
            }

3:

StringBuilder stringBuilder = new StringBuilder();
 foreach (var item in miltilines)
            {
 stringBuilder.AppendLine(item );
}

有没有办法从字符串数组中获取多行字符串对象

【问题讨论】:

  • #1 应该可以正常工作。是什么让你认为它没有
  • 我已经尝试过了,在对象中我得到“一条 minErr 消息有两部分:/r/n 消息本身和包含编码消息的 url。/r/n 消息的参数可以包含其他错误消息,其中也包括错误 url。"
  • but ended with \r\n in string object 这就是在 Visual Studio 调试窗口中表示换行符的方式。如果您将该字符串写入文件并在文本编辑器中打开,您将看到换行符。
  • 如果第三方工具在字符串包含换行符时给您异常,那么您不能传入多行字符串。多行字符串按定义包含\r\n。
  • 从您的样本中形成的字符串也包含\r\n。您刚刚使用@ 隐藏字符并在编辑器中显示格式化字符串。在该行之后设置一个断点并在调试器中查看该字符串。

标签: c# multilinestring


【解决方案1】:

如果您通过将原始代码分配给变量来测试原始代码:

var value = @"A minErr message has two parts: 
              the message itself and the url that contains the encoded message.
              The message's parameters can contain other error messages which also include error 
              urls.";

然后转到调试器窗口并检查value 变量,你会发现:

"A minErr message has two parts: \r\n  the message itself and the url that contains the encoded message.\r\n  The message's parameters can contain other error messages which also include error urls."

\r 和\n 是escape sequences:

转义序列通常用于指定操作,例如 终端和打印机上的回车和制表符移动。他们是 也用于提供非打印字符的文字表示 和通常具有特殊含义的字符,例如双精度 引号 (")。

方法 #1 应该可以正常工作。 Environment.NewLine 代表非打印字符:

对于非 Unix 平台,一个包含 "\r\n" 的字符串,或者一个字符串 对于 Unix 平台,包含“\n”。

因此它们不会打印为\r 或\n,而是分别被解释为回车和换行操作。

【讨论】:

    【解决方案2】:

    对于字符串,实际数据与向用户呈现的方式之间可能存在巨大差距。包括你,调试器的用户。如果你不知道如何解释一个字符串,你就无法得到字母,甚至无法弄清楚该死的东西在哪里结束: https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/

    调试器和 Windows/程序对于如何解释任何给定字符串有非常不同的想法并不少见。你的例子: “一条 minErr 消息有两部分:/r/n 消息本身和包含编码消息的 url。/r/n 消息的参数可以包含其他错误消息,其中也包括错误 url。”只是对您期望的字符串的一种可能的解释。

    调试器使用工具提示。这些工具提示不支持多行。这可能有技术原因(工具提示不支持换行符/第一次编写时不支持)或用例原因(这会使带有大量换行符的字符串难以阅读 Tolltips)。

    /r/n 是 Windows 上的“回车”和“换行”字符。由于缺乏在多行上实际显示内容的能力(如多行文本框),调试器做了下一个最好的事情:它将换行符转义字符显示为字符串的一部分。任何实际上可以在多行中显示文本的代码都会正确地将这些字符解释为它们应该表示的内容。

    【讨论】:

      猜你喜欢
      • 2019-07-30
      • 1970-01-01
      • 1970-01-01
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-31
      相关资源
      最近更新 更多