在新行(C#)中打印字符串
本文关键字:打印 字符串 新行 | 更新日期: 2023-09-27 18:16:51
我有一个奇怪的需求,类似于:
string a = @"test content {1} test content {2}"
打印时,我需要输出
test content {1}
test content {2}
因此,我尝试将'r'n
附加到字符串中,但它的打印结果如下:
string a = "test content {1}'r'n test content {2}'r'n"
输出:
test content {1}'r'n test content {2}'r'n
为什么会有这种行为?有什么想法吗?
问题出现在string
之前的启动@
中。
它告诉编译器退出下面的string
,所以实际上是这样的:
string s = "test content {1}''r''ntest content {2}"
卸下@
,它就会工作。
关于原始字符串-在字符串中包含换行符,@很重要!
string a = @"test content {1}
test content {2}";
输出将是:
test content
test content
string a = "test content {1}" + Environment.NewLine + " test content {2}" + Environment.NewLine;
Environment.NewLine转义一行。
我认为最好的方法是使用StringBuilder类,因为字符串是不可免疫的
StringBuilder strb = new StringBuilder();
strb.AppendLine("test content {1}");
strb.Append("test content {2}");
string a = strb.ToString();
在字符串中使用分隔符的事实,如
string a = "test content {1}'r'n test content {2}'r'n"
告诉代码将它们作为一个可显示的字符串处理-惊喜!我建议你把字符串分成不同的组,比如
string a = "test content {1}" + Environment.NewLine + "test content {2}";
您可以使用String.Format((和Environment.NewLine:
String.Format("test content {{1}}{0}test content {{2}}", Environment.NewLine)
用于转义此字符的双{}
。{0}
插入Environment.NewLine字符串。