如何插入新行的字符串? [英] How to insert newline in string literal?

查看:127
本文介绍了如何插入新行的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.NET中我可以同时提供 \ r 字符串,但有一个办法插入 像新线特殊字符,如 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?

推荐答案

好了,简单的选项有:

  • 的String.Format

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

  • 字符串连接:

  • String concatenation:

    string x = "first line" + Environment.NewLine + "second line";
    

  • 路线插值(在C#6及以上):

  • String interpolation (in C#6 and above):

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

  • 您也可使用\ n随处可见,并替换:

    You could also use \n everywhere, and replace:

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

    请注意,你不能让这个字符串的的,因为 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.

    这篇关于如何插入新行的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆