如何在字符串文字中插入换行符?

时间:2010-11-03 09:41:46

标签: c# .net line-breaks

在.NET中我可以提供\r\n字符串文字,但有一种方法可以插入 类似“新行”的特殊字符,如Environment.NewLine静态属性?

12 个答案:

答案 0 :(得分:285)

嗯,简单的选择是:

  • string.Format

    string x = string.Format("first line{0}second line", Environment.NewLine);
    
  • 字符串连接:

    string x = "first line" + Environment.NewLine + "second line";
    
  • 字符串插值(在C#6及以上版本中):

    string x = $"first line{Environment.NewLine}second line";
    

你也可以在任何地方使用\ n,并替换:

string x = "first line\nsecond line\nthird line".Replace("\n",
                                                         Environment.NewLine);

请注意,您不能将此字符串设为常量,因为Environment.NewLine的值仅在执行时可用。

答案 1 :(得分:29)

如果你想要一个包含Environment.NewLine的const字符串,你可以这样做:

const string stringWithNewLine =
@"first line
second line
third line";

修改

由于这是一个const字符串,它是在编译时完成的,因此它是编译器对换行符的解释。我似乎找不到解释这种行为的参考,但我可以证明它按预期工作。我在Windows和Ubuntu(使用Mono)上编译了这段代码,然后进行了反汇编,结果如下:

Disassemble on Windows Disassemble on Ubuntu

如您所见,在Windows中,换行符被解释为\ r \ n,在Ubuntu上被解释为\ n

答案 2 :(得分:12)

var sb = new StringBuilder();
sb.Append(first);
sb.AppendLine(); // which is equal to Append(Environment.NewLine);
sb.Append(second);
return sb.ToString();

答案 3 :(得分:3)

在格式字符串中方便地放置Environment.NewLine的另一种方法。 我们的想法是创建字符串扩展方法,像往常一样格式化字符串,但也用Environment.NewLine替换文本中的{nl}

<强> 用法

   " X={0} {nl} Y={1}{nl} X+Y={2}".FormatIt(1, 2, 1+2);
   gives:
    X=1
    Y=2
    X+Y=3

<强> 代码

    ///<summary>
    /// Use "string".FormatIt(...) instead of string.Format("string, ...)
    /// Use {nl} in text to insert Environment.NewLine 
    ///</summary>
    ///<exception cref="ArgumentNullException">If format is null</exception>
    [StringFormatMethod("format")]
    public static string FormatIt(this string format, params object[] args)
    {
        if (format == null) throw new ArgumentNullException("format");

        return string.Format(format.Replace("{nl}", Environment.NewLine), args);
    }

<强> 注意

  1. 如果您希望ReSharper突出显示您的参数,请将属性添加到上面的方法

    [StringFormatMethod(&#34;格式&#34)]

  2. 这种实现效率明显低于String.Format

  3. 也许对这个问题感兴趣的人也会对下一个问题感兴趣: Named string formatting in C#

答案 4 :(得分:2)

string myText =
    @"<div class=""firstLine""></div>
      <div class=""secondLine""></div>
      <div class=""thirdLine""></div>";
  

不是吗:

string myText =
@"<div class=\"firstLine\"></div>
  <div class=\"secondLine\"></div>
  <div class=\"thirdLine\"></div>";

答案 5 :(得分:1)

static class MyClass
{
   public const string NewLine="\n";
}

string x = "first line" + MyClass.NewLine + "second line"

答案 6 :(得分:1)

较新的.net版本允许您在文字前面使用$,这允许您使用内部变量,如下所示:

var x = $"Line 1{Environment.NewLine}Line 2{Environment.NewLine}Line 3";

答案 7 :(得分:0)

如果你真的想要New Line字符串作为常量,那么你可以这样做:

public readonly string myVar = Environment.NewLine;

C#中readonly关键字的用户意味着此变量只能分配给一次。您可以在其上找到文档here。它允许声明一个常量变量,其值在执行时间之前是未知的。

答案 8 :(得分:0)

我更喜欢&#34; pythonic方式&#34;

List<string> lines = new List<string> {
    "line1",
    "line2",
    String.Format("{0} - {1} | {2}", 
        someVar,
        othervar, 
        thirdVar
    )
};

if(foo)
    lines.Add("line3");

return String.Join(Environment.NewLine, lines);

答案 9 :(得分:0)

如果我理解这个问题:情侣&#34; \ r \ n&#34;在文本框中获取下面的新行。我的例子有效 -

string s1 = comboBox1.Text; // s1是分配给框1等的变量。    string s2 = comboBox2.Text;

string both = s1 +&#34; \ r \ n&#34; + s2;    textBox1.Text = both; 一个典型的答案可能是s1                           使用已定义的类型样式在文本框中输入s2。

答案 10 :(得分:0)

如果您正在使用Web应用程序,可以试试这个。

StringBuilder sb = new StringBuilder();
sb.AppendLine("Some text with line one");
sb.AppendLine("Some mpre text with line two");
MyLabel.Text = sb.ToString().Replace(Environment.NewLine, "<br />")

答案 11 :(得分:-1)

在这里,Environment.NewLine不起作用。

我在字符串中放入了“ << em> br / > ”并开始工作。

例如:

  

ltrYourLiteral.Text =“第一行。<< em> br / >第二行。