C#:字符串中的换行符和制表符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2157520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:01:22  来源:igfitidea点击:

C#: New line and tab characters in strings

c#

提问by burnt1ce

StringBuilder sb = new StringBuilder();
sb.Append("Line 1");
//insert new line character
//insert tab character
sb.Append("Line 2");
using (StreamWriter sw = new StreamWriter("example.txt"))
{
    sq.Write(sb.ToString());
}

How can insert a new line and tab character in this example?

在此示例中如何插入新行和制表符?

采纳答案by Patrick Desjardins

StringBuilder sb = new StringBuilder();
sb.Append("Line 1");
sb.Append(System.Environment.NewLine); //Change line
sb.Append("\t"); //Add tabulation
sb.Append("Line 2");
using (StreamWriter sw = new StreamWriter("example.txt"))
{
    sw.Write(sb.ToString());
}

You can find detailed documentationon TAB (and other escape character here).

您可以找到有关 TAB 的详细文档(以及此处的其他转义字符)。

回答by Dour High Arch

sb.Append(Environment.Newline);
sb.Append("\t");

回答by Keith Adler

sb.AppendLine();

or

或者

sb.Append( "\n" );

And

sb.Append( "\t" );

回答by John Feminella

Use:

用:

sb.AppendLine();
sb.Append("\t");

for better portability. Environment.NewLinemay not necessarily be \n; Windows uses \r\n, for example.

为了更好的便携性。Environment.NewLine不一定是\n\r\n例如,Windows 使用。

回答by Joshua

It depends on if you mean '\n' (linefeed) or '\r\n' (carriage return + linefeed). The former is not the Windows default and will not show properly in some text editors (like Notepad).

这取决于您的意思是 '\n'(换行)还是 '\r\n'(回车 + 换行)。前者不是 Windows 的默认设置,在某些文本编辑器(如记事本)中不会正确显示。

You can do

你可以做

sb.Append(Environment.NewLine);
sb.Append("\t");

or

或者

sb.Append("\r\n\t");

回答by dnxit

    StringBuilder SqlScript = new StringBuilder();

    foreach (var file in lstScripts)
    {
        var input = File.ReadAllText(file.FilePath);
        SqlScript.AppendFormat(input, Environment.NewLine);
    }

http://afzal-gujrat.blogspot.com/

http://afzal-gujrat.blogspot.com/