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

发布于 2024-09-30 13:53:37 字数 130 浏览 8 评论 0原文

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

In .NET I can provide both \r or \n string literals, but there is a way to insert
something like "new line" special character like Environment.NewLine static property?

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

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

发布评论

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

评论(12

江南月 2024-10-07 13:53:37

嗯,简单的选项是:

  • string.Format:

    string x = string.Format("第一行{0}第二行",Environment.NewLine);
    
  • 字符串连接:

    string x = "第一行" + Environment.NewLine + "第二行";
    
  • 字符串插值(C#6 及以上版本):

    string x = $"第一行{Environment.NewLine}第二行";
    

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

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

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

Well, simple options are:

  • string.Format:

    string x = string.Format("first line{0}second line", Environment.NewLine);
    
  • String concatenation:

    string x = "first line" + Environment.NewLine + "second line";
    
  • String interpolation (in C#6 and above):

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

You could also use \n everywhere, and replace:

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

Note that you can't make this a string constant, because the value of Environment.NewLine will only be available at execution time.

听闻余生 2024-10-07 13:53:37

如果您想要一个包含 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

If you want a const string that contains Environment.NewLine in it you can do something like this:

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

EDIT

Since this is in a const string it is done in compile time therefore it is the compiler's interpretation of a newline. I can't seem to find a reference explaining this behavior but, I can prove it works as intended. I compiled this code on both Windows and Ubuntu (with Mono) then disassembled and these are the results:

Disassemble on Windows
Disassemble on Ubuntu

As you can see, in Windows newlines are interpreted as \r\n and on Ubuntu as \n

榆西 2024-10-07 13:53:37
var sb = new StringBuilder();
sb.Append(first);
sb.AppendLine(); // which is equal to Append(Environment.NewLine);
sb.Append(second);
return sb.ToString();
var sb = new StringBuilder();
sb.Append(first);
sb.AppendLine(); // which is equal to Append(Environment.NewLine);
sb.Append(second);
return sb.ToString();
多情出卖 2024-10-07 13:53:37

在格式字符串中方便放置 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. 也许,对这个问题感兴趣的人也会对下一个问题感兴趣:
    C# 中的命名字符串格式

One more way of convenient placement of Environment.NewLine in format string.
The idea is to create string extension method that formats string as usual but also replaces {nl} in text with Environment.NewLine

Usage

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

Code

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

Note

  1. If you want ReSharper to highlight your parameters, add attribute to the method above

    [StringFormatMethod("format")]

  2. This implementation is obviously less efficient than just String.Format

  3. Maybe one, who interested in this question would be interested in the next question too:
    Named string formatting in C#

甜尕妞 2024-10-07 13:53:37
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>";
string myText =
    @"<div class=""firstLine""></div>
      <div class=""secondLine""></div>
      <div class=""thirdLine""></div>";

that's not it:

string myText =
@"<div class=\"firstLine\"></div>
  <div class=\"secondLine\"></div>
  <div class=\"thirdLine\"></div>";
梦回梦里 2024-10-07 13:53:37

如果你确实希望New Line字符串作为常量,那么你可以这样做:

public readonly string myVar = Environment.NewLine;

C#中readonly关键字的使用者意味着这个变量只能被赋值一次。您可以在此处找到相关文档。它允许声明一个常量变量,其值在执行时才知道。

If you really want the New Line string as a constant, then you can do this:

public readonly string myVar = Environment.NewLine;

The user of the readonly keyword in C# means that this variable can only be assigned to once. You can find the documentation on it here. It allows the declaration of a constant variable whose value isn't known until execution time.

倾城泪 2024-10-07 13:53:37
static class MyClass
{
   public const string NewLine="\n";
}

string x = "first line" + MyClass.NewLine + "second line"
static class MyClass
{
   public const string NewLine="\n";
}

string x = "first line" + MyClass.NewLine + "second line"
淤浪 2024-10-07 13:53:37

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

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

newer .net versions allow you to use $ in front of the literal which allows you to use variables inside like follows:

var x = $"Line 1{Environment.NewLine}Line 2{Environment.NewLine}Line 3";
—━☆沉默づ 2024-10-07 13:53:37

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

If you are working with Web application you can try this.

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 />")
謌踐踏愛綪 2024-10-07 13:53:37

如果我理解这个问题:结合“\r\n”以在文本框中获取下面的新行。我的示例有效 -

   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;

典型的答案可能是 s1
文本框中的s2使用定义的类型样式。

If I understand the question: Couple "\r\n" to get that new line below in a textbox. My example worked -

   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;

A typical answer could be s1
s2 in the text box using defined type style.

深爱不及久伴 2024-10-07 13:53:37

我更喜欢“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);

I like more the "pythonic way"

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);
つ可否回来 2024-10-07 13:53:37

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

我将“br/>”放入字符串中并工作。

前任:

ltrYourLiteral.Text = "第一行。br/>第二行。";

Here, Environment.NewLine doesn't worked.

I put a "<br/>" in a string and worked.

Ex:

ltrYourLiteral.Text = "First line.<br/>Second Line.";

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