简体   繁体   English

将多行字符串添加到另一个字符串=丢失多行?

[英]Add a multi-line string to another string = lose multi-line?

I wish to create a string that contains a list of stuff with one item on each line, but the following code doesn't maintain the new lines: 我希望创建一个字符串,其中包含每行包含一个项目的东西列表,但以下代码不维护新行:

foreach (DateTime date in dates)
{
    datelist += date.ToString("yyyy/MM/dd") + Environment.NewLine;
}

string mystring = String.Format(@"Hey there here is a list of dates

                                  Dates:

                                  {0}",
                                  datelist);

Output: 输出:

Hey there here is a list of dates 嘿,这里有一份日期清单

Dates: 日期:

2012/03/04 2012/03/05 2012/03/06 2012/03/04 2012/03/05 2012/03/06

Desired output: 期望的输出:

Hey there here is a list of dates 嘿,这里有一份日期清单

Dates: 日期:

2012/03/04 2012/03/04

2012/03/05 2012/03/05

2012/03/06 2012/03/06

I tried variations, such as two Environment.NewLines, escapes like \\r\\n, starting the string with @, and so on, and I could not get my desired output. 我试过变种,比如两个Environment.NewLines,像\\ r \\ n一样转义,用@开始字符串,依此类推,我无法得到我想要的输出。

I was ultimately able to solve my problem by putting a symbol into the string where I want linebreaks, and then use string.Replace to change the symbol to Environment.NewLine: 我最终能够通过将符号放入我想要换行的字符串来解决我的问题,然后使用string.Replace将符号更改为Environment.NewLine:

foreach (DateTime date in dates)
{
    datelist += date.ToString("yyyy/MM/dd") + "<br />";
}

string mystring = String.Format(@"Hey there here is a list of dates

                                  Dates:

                                  {0}",
                                  datelist.Replace(Environment.NewLine, "<br />"));

Like I said, this works, but I wish to know why good old concatenation doesn't work when inserting a string with lines into another string, as well as what the standard/common solution to my question would be. 就像我说的,这是有效的,但我想知道为什么在将带有行的字符串插入另一个字符串时,旧的连接不起作用,以及我的问题的标准/通用解决方案是什么。

If you render HTML output, you shouldn't use Environment.NewLine - use <br /> instead. 如果渲染HTML输出,则不应使用Environment.NewLine - 而是使用<br /> Multiple consecutive whitespace (including \\r and \\n ) may be aggregated by the browser into a single whitespace. 浏览器可以将多个连续的空格(包括\\r\\n )聚合到一个空格中。 (Based on my experience, the actual behavior is somewhat browser dependent but I didn't actually research into this.) (根据我的经验,实际行为在某种程度上取决于浏览器,但我实际上并没有对此进行研究。)

foreach (DateTime date in dates)
{
    datelist += date.ToString("yyyy/MM/dd") + "<br />";
}

string mystring = String.Format("Hey there here is a list of dates<br />" +
    "Dates:<br />{0}", datelist);

If somewhere within the string you need multiple blank lines, use multiple <br /> -s, of course. 如果字符串中的某个位置需要多个空行,当然要使用多个<br /> -s。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM