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

问题描述 投票:151回答:12

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

c# .net line-breaks
12个回答
311
投票

嗯,简单的选择是:

  • 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);

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


0
投票

如果您正在使用Web应用程序,则可以尝试此操作。


0
投票

如果我理解问题,请耦合"\r\n"以在textbox中获得以下新行。我的示例有效-


-1
投票

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


33
投票

如果要在其中包含Environment.NewLine的const字符串,则可以执行以下操作:

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

编辑

由于这是在const字符串中,所以它是在编译时完成的,因此它是编译器对换行符的解释。我似乎找不到解释此行为的参考,但是,我可以证明它可以正常工作。我在Windows和Ubuntu(带有Mono)上都编译了此代码,然后反汇编了,结果如下:

“在Windows上反汇编”“在Ubuntu上反汇编”

您可以看到,在Windows中,换行符解释为\ r \ n,而在Ubuntu上则解释为\ n


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

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(“ format”)]

    ] >>
  2. 此实现显然不如String.Format

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

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>";
static class MyClass
{
   public const string NewLine="\n";
}

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

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

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

如果您确实希望将换行符字符串作为常量,则可以这样做:

public readonly string myVar = Environment.NewLine;

C#中readonly关键字的用户意味着该变量只能分配一次。您可以在其中找到文档here。它允许声明一个常量变量,其值直到执行时才知道。

我更喜欢“ pythonic方式”

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

如果您正在使用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 />")

如果我理解问题,请耦合"\r\n"以在textbox中获得以下新行。我的示例有效-

   string s1 = comboBox1.Text;     // s1 is the variable assigned to box 1, etc.
   string s2 = comboBox2.Text;

   string both = s1 + "\r\n" + s2;
   textBox1.Text = both;

典型的答案可能是s1s2中的text box使用定义的字体样式。

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

我在字符串中放入了“ << [br /] >>

”并起作用。 例如:

ltr​​YourLiteral.Text =“第一行。<< [br /] >>第二行。”;

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

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

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

1
投票

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


0
投票

如果您确实希望将换行符字符串作为常量,则可以这样做:


0
投票

我更喜欢“ pythonic方式”

© www.soinside.com 2019 - 2024. All rights reserved.